Java JDBC数据操作封装

Java的JDBC数据操作封装

package com.xu.dao;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


public class DBHelper {
    //private static DataSource dataSource;
    private Connection connection=null;
    private PreparedStatement pstmt=null;
    private ResultSet rsultset=null;

    static{
        try {
            //Context context = new  InitialContext();
            //dataSource = (DataSource) context.lookup("java:comp/env/jdbc/product"); 
            Class.forName(MyProperties.getInstance().getProperty("driverClassName"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public  Connection getConnection(){
        Connection connection = null;
        try {
            //connection=(Connection) DriverManager.getConnection(MyProperties.getInstance().getProperty("url"),MyProperties.getInstance().getProperty("username"),MyProperties.getInstance().getProperty("password"));
            connection=(Connection) DriverManager.getConnection(MyProperties.getInstance().getProperty("url"),MyProperties.getInstance().getProperty("username"),MyProperties.getInstance().getProperty("password"));
        } catch (SQLException e) {
            e.printStackTrace();
        }

        //      if (dataSource != null){
        //          try {
        //              //connection = dataSource.getConnectionection();  
        //              connection=(Connection) DriverManager.getConnectionection(MyProperties.getInstance().getProperty("url"),MyProperties.getInstance().getProperty("username"),MyProperties.getInstance().getProperty("password"));
        //          } catch (SQLException e) {
        //              e.printStackTrace();
        //          } 
        //      }
        return connection;
    }

    //class反射
    /**
     * 关闭的方法
     */
    public void closeAll(Connection connection,PreparedStatement pstmt,ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
            	e.printStackTrace();
            }
        }
        if(pstmt!=null){
            try {
                pstmt.close();
            } catch (SQLException e) {
            	e.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
            	e.printStackTrace();
            }
        }
    }

	/**
	 * 设置预编译数据
	 * @param pstmt  预编译对象
	 * @param params 预编译数据
	 */
	public void setValues(PreparedStatement pstmt,List<Object> params){
		if(pstmt!=null&&params!=null&&params.size()>0){
			String type=null;
			for(int i=0;i<params.size();i++){
				Object object=params.get(i);
				try {
					if(object!=null){
						type=object.getClass().getName();
						if("javax.sql.rowset.serial.SerialBlob".equals(type)){//javax.sql.rowset.serial.SerialBlob
							pstmt.setBlob(i+1, (Blob)params.get(i));
						}else if("java.lang.Integer".equals(type)){//java.lang.Integer
							pstmt.setInt(i+1,Integer.parseInt(String.valueOf(object)));
						}else if("java.lang.Double".equals(type)){//java.lang.Double
							pstmt.setDouble(i+1, Double.parseDouble(String.valueOf(object)));
						}else if("java.lang.Float".equals(type)){//java.lang.Float
							pstmt.setDouble(i+1, Float.parseFloat(String.valueOf(object)));
						}else if("java.lang.Long".equals(type)){//java.lang.Long
							pstmt.setLong(i+1, Long.parseLong(String.valueOf(object)));
						}else if("java.lang.Short".equals(type)){//java.lang.Short
							pstmt.setShort(i+1, Short.parseShort(String.valueOf(object)));
						}else if("java.lang.String".equals(type)){//java.lang.String
							pstmt.setString(i+1,String.valueOf(object));
						}else if("java.lang.Timestamp".equals(type)){//java.sql.Timestamp 
							pstmt.setTimestamp(i+1,(Timestamp)params.get(i));
						}else{                    	 
							pstmt.setString(i+1,String.valueOf(object));
						}
					}else{
						pstmt.setString(i+1,"");
					}

				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 设置预编译数据
	 * @param pstmt 预编译对象
	 * @param objs  预编译数据
	 */
	public void setValues(PreparedStatement pstmt,Object ... objs){
		if(pstmt!=null&&objs!=null&&objs.length>0){
			String type=null;
			for(int i=0,len=objs.length;i<len;i++){
				Object object=objs[i];
				try {
					if(object!=null){
						type=object.getClass().getName();
						if("javax.sql.rowset.serial.SerialBlob".equals(type)){//javax.sql.rowset.serial.SerialBlob
							pstmt.setBlob(i+1, (Blob)objs[i]);
						}else if("java.lang.Integer".equals(type)){//java.lang.Integer
							pstmt.setInt(i+1,Integer.parseInt(String.valueOf(object)));
						}else if("java.lang.Double".equals(type)){//java.lang.Double
							pstmt.setDouble(i+1, Double.parseDouble(String.valueOf(object)));
						}else if("java.lang.Float".equals(type)){//java.lang.Float
							pstmt.setDouble(i+1, Float.parseFloat(String.valueOf(object)));
						}else if("java.lang.Long".equals(type)){//java.lang.Long
							pstmt.setLong(i+1, Long.parseLong(String.valueOf(object)));
						}else if("java.lang.Short".equals(type)){//java.lang.Short
							pstmt.setShort(i+1, Short.parseShort(String.valueOf(object)));
						}else if("java.lang.String".equals(type)){//java.lang.String
							pstmt.setString(i+1,String.valueOf(object));
						}else if("java.lang.Timestamp".equals(type)){//java.sql.Timestamp 
							pstmt.setTimestamp(i+1,(Timestamp)objs[i]);
						}else{                    	 
							pstmt.setString(i+1,String.valueOf(object));
						}
					}else{
						pstmt.setString(i+1,"");
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 多SQL增删改(不建议使用)
	 * @param sql    sql语句(使用?作为占位符)
	 * @param params sql语句参数
	 * @return 结果(-1代表失败,大于0表示成功)
	 */
	public int update(List<String> sql,List<List<Object>> params){
		connection=this.getConnection();
		int result=0;  
		try {
			connection.setAutoCommit(false);  //事务处理
			for(int i=0;i<sql.size();i++){
				List<Object> param=params.get(i);
				pstmt=connection.prepareStatement(sql.get(i));  //预编译对象
				setValues(pstmt,param);    //设置参数
				result=pstmt.executeUpdate();
			}
			connection.commit(); //没有错处执行
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				connection.rollback();  //出错回滚
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}finally{
			closeAll(connection,pstmt,null);
		}
		return result;
	}

	/**
	 * 单表增删改
	 * @param sql     sql语句
	 * @param params  参数
	 * @return 结果(-1代表失败,大于0表示成功)
	 */
	public int update(String sql,List<Object> params){
		connection=this.getConnection();
		int result=0;
		try {
			pstmt=connection.prepareStatement(sql);//预编译对象
			setValues(pstmt,params);//设置参数
			result=pstmt.executeUpdate();
		} catch (SQLException e) {
			try {
				connection.rollback();  //出错回滚
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}finally{
			closeAll(connection,pstmt,null);
		}
		return result;
	}

	/**
	 * 单表增删改
	 * @param sql    sql语句
	 * @param params 参数
	 * @return  结果(-1代表失败,大于0表示成功)
	 */
	public int update(String sql,Object ... params){
		connection=this.getConnection();
		int result=0;
		try {
			pstmt=connection.prepareStatement(sql);  //预编译对象
			setValues(pstmt,params);    //设置参数
			result=pstmt.executeUpdate();
		} catch (SQLException e) {
			try {
				connection.rollback();  //出错回滚
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}finally{
			closeAll(connection,pstmt,null);
		}

		return result;
	}



	/**
	 * 多SQL查询(不建议使用)
	 * @param sql    sql语句(使用?作为占位符)
	 * @param params sql语句参数
	 * @return 结果
	 */
	public List<String> find(String sql,List<Object> params){
		List<String> list=new ArrayList<String>();
		connection=this.getConnection();
		try {
			pstmt=connection.prepareStatement(sql);  //预编译对象
			setValues(pstmt,params);   //设置参数
			rsultset=pstmt.executeQuery();  //执行查询

			ResultSetMetaData md=rsultset.getMetaData();  //结果集的元数据,它反映了结果集的信息
			int count=md.getColumnCount();    //取出结果集中列的数量

			if(rsultset.next()){
				for(int i=1;i<=count;i++){
					list.add(rsultset.getString(i));
				}
			}
		} catch (SQLException e) {
			//TODO:
		}finally{
			closeAll(connection,pstmt,rsultset);
		}
		return list;
	}

	/**
	 * 单表查询
	 * @param sql    sql语句(使用?作为占位符)
	 * @param params sql语句参数
	 * @return 结果
	 */
	public List<String> find(String sql,Object ... params){
		List<String> list=new ArrayList<String>();
		connection=this.getConnection();
		try {
			pstmt=connection.prepareStatement(sql);  //预编译对象
			setValues(pstmt,params);   //设置参数
			rsultset=pstmt.executeQuery();  //执行查询

			ResultSetMetaData md=rsultset.getMetaData();  //结果集的元数据,它反映了结果集的信息
			int count=md.getColumnCount();    //取出结果集中列的数量

			if(rsultset.next()){
				for(int i=1;i<=count;i++){
					list.add(rsultset.getString(i));
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(connection,pstmt,rsultset);
		}
		return list;
	}

	/**
	 * 单表查询
	 * @param sql sql语句
	 * @param c   JavaBean
	 * @param params sql语句参数 
	 * @return  结果
	 * @throws NumberFormatException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	public <T> List<T> find(String sql,Class<T> c ,List<Object> params) throws NumberFormatException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		if( params==null){
			return find(sql,c);
		}else{
			return find(sql,c,params.toArray());    
		}

	}

	private Set<String> getMethodName(Set<String> keys){
		Set<String> result=new HashSet<String>();
		for(String key:keys){
			String newName="set"+key.substring(0,1).toUpperCase()+key.substring(1);
			result.add(newName);
		}
		return result;
	}

	/**
	 * 单表查询
	 * @param sql sql语句
	 * @param c   JavaBean
	 * @param params sql语句参数 
	 * @return  结果
	 * @throws NumberFormatException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	public <T> List<T> find(String sql,Class<T> c,Object ... params) throws InstantiationException, IllegalAccessException, NumberFormatException, IllegalArgumentException, InvocationTargetException{
		List<Map<String, Object>> listMap=finds(sql,params);
		List <T> list=new ArrayList<T>(); //要返回的结果的集合
		T t=null;
		connection=this.getConnection();
		if(  listMap==null|| listMap.size()<=0){
			return list;
		}
		Map<String,Object> map=listMap.get(0);
		Set<String> keys=map.keySet();
		Set<String> methodNames=getMethodName(keys);//拼接方法
		Method[] ms=c.getMethods();
		for(  Map<String,Object> m:listMap){
			t=(T)c.newInstance();
			for(  Method method:ms){//这个是获取的方法
				for(String mn:methodNames){//这个是拼接的方法
					if(  method.getName().equals(mn)){
						String keyname=mn.substring(3,4).toLowerCase()+mn.substring(4);
						String typeName=method.getParameterTypes()[0].getName();
						if( "java.lang.Integer".equals(typeName)|| "int".equals(typeName)){
							method.invoke(t,Integer.parseInt(m.get(keyname).toString()));
						}else if( "java.lang.Double".equals(typeName)|| "double".equals(typeName)){
							method.invoke(t,Double.parseDouble(m.get(keyname).toString()));
						}else if( "java.lang.Float".equals(typeName)|| "float".equals(typeName)){
							method.invoke(t,Float.parseFloat(m.get(keyname).toString()));
						}else if( "java.lang.Long".equals(typeName)|| "long".equals(typeName)){
							method.invoke(t,Long.parseLong(m.get(keyname).toString()));
						}else {
							method.invoke(t,m.get(keyname).toString());
						}
						break;
					}
				}
			}
			list.add(t);
		}   
		return list;
	}


	/**
	 * 单表查询
	 * @param sql    sql语句
	 * @param params sql语句参数 
	 * @return  结果
	 */
	public List<Map<String,Object>> finds(String sql,List<Object> params){
		if(params==null){
			return finds(sql);
		}else{
			return finds(sql, params.toArray());
		}
	}

	/**
	 * 单表查询
	 * @param sql    sql语句
	 * @param params sql语句参数 
	 * @return  结果
	 */
	public List<Map<String,Object>> finds(String sql,Object ... objs){
		List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
		connection=this.getConnection();
		try {
			pstmt=connection.prepareStatement(sql);
			this.setValues(pstmt,objs);//给占位符赋值
			rsultset=pstmt.executeQuery();//获取结果集
			//获取返回结果中的列的列名
			ResultSetMetaData rsmd=rsultset.getMetaData();
			int colLen=rsmd.getColumnCount(); //获取结果集中列的数量
			String[] colNames=new String[colLen];
			for(int i=0;i<colLen;i++){//取出每个列的列名存放到数组中
				colNames[i]=rsmd.getColumnName(i+1);
			}
			Map<String,Object> map=null;
			String typeName;
			Object obj;
			while(rsultset.next()){//循环取值,每循环一次就是一条记录,存放到一个map中
				map=new HashMap<String,Object>();
				for(int i=0;i<colLen;i++){ //循环取出每个列的值
					obj=rsultset.getObject(colNames[i]);
					if(obj!=null){
						typeName=obj.getClass().getSimpleName();
						if("BLOB".equals(typeName)){
							Blob blob=rsultset.getBlob(colNames[i]);
							byte[] bt=null;
							BufferedInputStream bis=null;
							try {
								bis=new BufferedInputStream( blob.getBinaryStream());
								bt=new byte[(int) blob.length()];
								bis.read(bt);
								map.put(colNames[i],bt);
							} catch (IOException e) {
								e.printStackTrace();
							}  finally{
								if(bis!=null){
									try {
										bis.close();
									} catch (Exception e) {
										e.printStackTrace();
									}
								}
							}
						}else{
							map.put(colNames[i],rsultset.getString(colNames[i])); 
						}
					}else{
						map.put(colNames[i],""); //以当前列的列名为键,以当前列的值为值
					}
				}
				list.add(map);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			this.closeAll(connection, pstmt, rsultset);
		}
		return list;
	}

}

使用方法

public class Test{
	public static void main(String[] args){
		DBHelper helper=new DBHeloer();
		//这里是用?来作为SQL的占位符
		String sql="select * from student where id=? and name=?";
		List list =new ArrayList();
		list.add(123456);
		list.add("张三");
		List student=helper.find(sql,list,Student.class);
	}
}

 
  

                            
                        
                    
                    
                    

你可能感兴趣的:(Java,数据库,JDBC封装)