JDBC操作封装实例

2018-01-05  本文已影响0人  hey_leex

JDBC操作封装实例

JDBCUtile.properties

drv=com.mysql.jdbc.Driver
url=jdbc:mysql:///myHomePage
uid=root
pwd=root

JDBCUtile

/**
 * JDBC工具类
 * @author leex
 *
 */
public class JDBCUtils {
    //创建Properties文件对象
    private static Properties prop = new Properties();
    //创建ThreadLocal线程锁
    private static ThreadLocal<Connection> treadLocal = new ThreadLocal<Connection>();
    
    static {
        //TWR语法创建Properties文件输入流
        //JDBCUtils.class.getClassLoader().getResourceAsStream("JDBC.properties")通过类加载器获取文件完全路径
        try (InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("JDBC.properties")){
            //加载Properties文件
            prop.load(in);
            //加载数据库驱动
            Class.forName(prop.getProperty("drv"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 获取Connection对象的方法
     * @return  Connection对象
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        //获取与此线程绑定的Connection
        Connection conn = treadLocal.get();
        //如果不为空返回
        if(null != conn) {
            return conn;
        }
        //如果为空创建新的
        conn = DriverManager.getConnection(
                prop.getProperty("url"), prop.getProperty("uid"), prop.getProperty("pwd"));
        //把创建的线程绑定到线程
        treadLocal.set(conn);
        return conn;
    }
    
    /**
     * 关闭Connection
     * @throws SQLException
     */
    public static void close() throws SQLException {
        Connection conn = treadLocal.get();
        if(null != conn) {
            conn.close();
            //从线程绑定中移除
            treadLocal.remove();
        }
    }
}

BaseDao

/**
 * 封装的JDBC基础操作类
 * @author leex
 *
 */
public class BaseDao {
    
    /**
     * 更新方法
     * @param sql       sql语句
     * @param paramers  占位符的值
     * @return
     * @throws SQLException
     */
    public int update(String sql ,Object...paramers) throws SQLException {
        //通过JDBCUtils获取Connection连接
        Connection conn = JDBCUtils.getConnection();
        //创建PreparedStatement对象
        PreparedStatement statm = conn.prepareStatement(sql);
        //创建PreparedStatement元数据
        ParameterMetaData parameterMetaData = statm.getParameterMetaData();
        //通过PreparedStatement元数据获取数据库中的字段数
        int count = parameterMetaData.getParameterCount();
        //判断输入的值数量是否正确(提高程序健壮性)
        if(null != paramers) {
            if(count != paramers.length) {
                throw new RuntimeException("传入的参数有错误....");
            }
        }
        //给sql语句中的占位符赋值
        for (int i = 0; i < paramers.length; i++) {
            statm.setObject(i + 1, paramers[i]);
        }
        //更新
        int executeUpdate = statm.executeUpdate();
        //关闭connection
        JDBCUtils.close();
        //返回收影响的行数
        return executeUpdate;
    }
    
    /**
     * 通用查询方法
     * @param sql           sql语句   
     * @param clazz         返回的封装类
     * @param paramers      sql占位符值
     * @return
     * @throws SQLException
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public <T> List<T> queryList(String sql, Class clazz, Object... paramers ) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
        List<T> list = new ArrayList<>();
        
        //通过JDBCUtils获取Connection连接
        Connection conn = JDBCUtils.getConnection();
        //创建PreparedStatement对象
        PreparedStatement statm = conn.prepareStatement(sql);
        //创建PreparedStatement元数据
        ParameterMetaData parameterMetaData = statm.getParameterMetaData();
        //通过PreparedStatement元数据获取数据库中的字段数
        int count = parameterMetaData.getParameterCount();
        //判断输入的值数量是否正确(提高程序健壮性)
        if(null != paramers) {
            if(count != paramers.length) {
                throw new RuntimeException("传入的参数有错误....");
            }
        }
        if(0 != paramers.length)
        for (int i = 0; i < paramers.length; i++) {
            statm.setObject(i + 1, paramers[i]);
        }
        //获取结果集
        ResultSet result = statm.executeQuery();
        //创建结果集元数据
        ResultSetMetaData metaData = result.getMetaData();
        //获取结果集的列数
        int columnCount = metaData.getColumnCount();
        //遍历结果集
        while(result.next()) {
            //创建对象
            T t = (T) clazz.newInstance();
            //给对象赋值
            for (int i = 0; i < columnCount; i++) {
                //获取结果集的列名(有别名则就是别名)
                String columnName = metaData.getColumnLabel(i+1);
                //获取值
                Object value = result.getObject(columnName);
                //通过BeanUtils匹配赋值
                BeanUtils.copyProperty(t, columnName, value);
            }
            //加入列表
            list.add(t);
        }
        //关闭connection
        JDBCUtils.close();
        //返回list
        return list;
    }
}
上一篇下一篇

猜你喜欢

热点阅读