一、数据库封装的主体方法,主要是将数据的增删改放在一个函数里面,通过java的隐式参数来进行参数的传递,以及反射的使用,步骤如下:
1.对数据库驱动连接
2.数据库连接
3.数据库的增删改的通用方法
4.单行数据的查询
5.单行单列数据的查询
6.多行数据的查询
7.判断列的类型
8.获取列的数据
9.层次关闭所有连接
/**
* JDBC的数据访问辅助类
* @author Administrator
*
*/
public class JdbcHandler {
private static String driver;
private static String url;
private static String user;
private static String password;
static{
try {
ResourceBundle bundle = ResourceBundle.getBundle("config");
driver = bundle.getString("driver");
url = bundle.getString("url");
user = bundle.getString("user");
password = bundle.getString("password");
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取数据库连接
* @return
*/
public static Connection getConnection(){
Connection con = null;
try {
con = DriverManager.getConnection(url,user,password);
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
/**
* 关闭数据库对象
* @param con
* @param stmt
* @param rs
*/
public static void closeAll(Connection con, Statement stmt, ResultSet rs){
try {
if(rs != null){
rs.close();
}
if(stmt != null){
stmt.close();
}
if(con != null){
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 增删改查的通用方法
* @param sql SQL语句
* @param params 需要注入的参数
* @return
*/
public static boolean executeUpdate(String sql, Object[] params){
Connection con = getConnection();
PreparedStatement pstmt = null;
if(con != null){
try {
pstmt = con.prepareStatement(sql);
if(pstmt != null){
for(int i = 0; i < params.length; i++){
if(params[i].getClass() == Date.class){
pstmt.setTimestamp(i+1, new Timestamp(((Date)params[i]).getTime()));
}
else{
pstmt.setObject(i+1, params[i]);
}
}
}
return pstmt.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
}
finally{
closeAll(con, pstmt, null);
}
}
return false;
}
/**
* 查询单行数据的方法
* @param
* @param sql
* @param params
* @return
*/
public static T executeQueryForSingle(String sql, Object[] params, Class classT){
T t = null;
Connection con = getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null;
if(con != null){
try {
pstmt = con.prepareStatement(sql);
if(params != null){
for(int i = 0; i < params.length; i++){
if(params[i].getClass() == Date.class){
pstmt.setTimestamp(i+1, new Timestamp(((Date)params[i]).getTime()));
}
else{
pstmt.setObject(i+1, params[i]);
}
}
}
rs = pstmt.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
List columnList = JdbcUtil.parseMetaData(metaData);
Field[] fields = classT.getDeclaredFields();
Method[] methods = classT.getMethods();
while(rs.next()){
t = (T)classT.newInstance();
executeQueryForColData(columnList,rs,fields,methods,t);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
finally{
closeAll(con, pstmt, rs);
}
}
return t;
}
/**
* 判断列的数据类型,从而获得数据
* @param type
* @param index
* @return
*/
private static Object validateTypeForData(Object value, ResultSet rs, int type, int index){
try {
if(type == OracleTypes.VARCHAR){
value = rs.getString(index+1);
}
else if(type == OracleTypes.INTEGER){
value = rs.getInt(index+1);
}
else if(type == OracleTypes.FLOAT){
value = rs.getDouble(index+1);
}
else if(type == OracleTypes.NUMBER){
BigDecimal num = rs.getBigDecimal(index+1);
if(num != null){
if(JdbcUtil.isInteger(num)){
value = rs.getInt(index+1);
}
else{
value = rs.getDouble(index+1);
}
}
}
else if(type == OracleTypes.DATE){
value = rs.getTimestamp(index+1);
}
else if(type == OracleTypes.CLOB){
Clob clob = rs.getClob(index+1);
if(clob != null){
BufferedReader reader = new BufferedReader(clob.getCharacterStream());
StringBuffer buffer = new StringBuffer();
String s = "";
try {
while((s = reader.readLine()) != null){
buffer.append(s);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
value = buffer.toString();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return value;
}
/**
* 获取每列的数据
* @param
* @param columnList
* @param rs
* @param fields
* @param methods
* @param t
*/
private static void executeQueryForColData(List columnList, ResultSet rs, Field[] fields, Method[] methods,T t){
try {
for(int i = 0; i < columnList.size(); i++){
ColumnInfo col = columnList.get(i);
int type = col.getColumnType();
String columnName = col.getColumnName();
Object value = null;
Object newvalue = validateTypeForData(value,rs,type,i);
boolean hasField = false;
String fieldName = null;
if(fields != null){
for(int j = 0; j < fields.length; j++){
if(fields[j].getName().toUpperCase().equals(columnName)){
hasField = true;
fieldName = fields[j].getName();
break;
}
}
}
if(methods != null && hasField){
for(int j = 0; j < methods.length; j++){
if(methods[j].getName().equals("set"+JdbcUtil.parseFirstUpper(fieldName))){
methods[j].invoke(t, newvalue);
break;
}
}
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* 查询多行数据的方法
* @param
* @param sql
* @param params
* @return
*/
public static List executeQueryForMutiple(String sql, Object[] params, Class classT){
T t = null;
Connection con = getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null;
List list = new ArrayList();
if(con != null){
try {
pstmt = con.prepareStatement(sql);
if(params != null){
for(int i = 0; i < params.length; i++){
if(params[i].getClass() == Date.class){
pstmt.setTimestamp(i+1, new Timestamp(((Date)params[i]).getTime()));
}
else{
pstmt.setObject(i+1, params[i]);
}
}
}
rs = pstmt.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
List columnList = JdbcUtil.parseMetaData(metaData);
Field[] fields = classT.getDeclaredFields();
Method[] methods = classT.getMethods();
while(rs.next()){
t = (T)classT.newInstance();
executeQueryForColData(columnList,rs,fields,methods,t);
list.add(t);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
finally{
closeAll(con, pstmt, rs);
}
}
return list;
}
/**
* 查询单行单列数据
* @param sql
* @param params
* @param type
* @return
*/
public static Object executeQueryForColRow(String sql, Object[] params,int type){
Object value = null;
Object newvalue = null;
Connection con = getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null;
if(con != null){
try {
pstmt = con.prepareStatement(sql);
if(params != null){
for(int i = 0; i < params.length; i++){
pstmt.setObject(i+1, params[i]);
}
}
rs = pstmt.executeQuery();
while(rs.next()){
newvalue = validateTypeForData(value,rs,type,0);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return newvalue;
}
}
二、辅助方法,主要是返回列及其类型,和一些数据的类型判断。
/**
* JDBC数据访问工具类
* @author Administrator
*
*/
public class JdbcUtil {
/**
* 解析元数据的结构
* @param metaData
* @return 结果集每个列的数据类型和列名
*/
public static List parseMetaData(ResultSetMetaData metaData){
ArrayList list = new ArrayList();
try {
for(int i = 0; i < metaData.getColumnCount(); i++){
ColumnInfo col = new ColumnInfo(metaData.getColumnName(i+1), metaData.getColumnType(i+1));
list.add(col);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
/**
* 判断是否是整数
* @param num
* @return true表示为int false表示为浮点值
*/
public static boolean isInteger(BigDecimal num){
if(num.toString().indexOf(".") == -1){
return true;
}
return false;
}
/**
* 对首字母进行大写转换的方法
* @param fieldName
*/
public static String parseFirstUpper(String fieldName){
char first = fieldName.charAt(0);
first = (char)((int)first-32);
return first+fieldName.substring(1);
}
public static Date stringToDate(String time, String pattern) throws ParseException{
return new SimpleDateFormat(pattern).parse(time);
}
public static String dateToString(Date time, String pattern){
return new SimpleDateFormat(pattern).format(time);
}
public static Date getDateByFormat(Date time, String pattern) throws ParseException{
return stringToDate(dateToString(time,pattern),"yyyy-MM-dd");
}
public static Calendar dateTocalendar(Date time){
Calendar cal = Calendar.getInstance();
cal.setTime(time);
return cal;
}
public static boolean valitadeIsWeekend(Calendar cal){
if(cal.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY||cal.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY)
{
return false;
}
return true;
}
}
三、关于列的封装类
public class ColumnInfo {
private String columnName;
private int columnType;
public ColumnInfo(String columnName, int columnType) {
super();
this.columnName = columnName;
this.columnType = columnType;
}
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public int getColumnType() {
return columnType;
}
public void setColumnType(int columnType) {
this.columnType = columnType;
}
}