美文网首页
JDBC操作封装实例

JDBC操作封装实例

作者: hey_leex | 来源:发表于2018-01-05 17:41 被阅读0次

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;
    }
}

相关文章

  • JDBC操作封装实例

    JDBC操作封装实例 JDBCUtile.properties JDBCUtile BaseDao

  • 简介

    什么是mybatis mybatis是对jdbc技术的封装,简化数据库操作代码。 封装以下功能:--封装了建立连接...

  • 三、 Spring JDBC(了解)

    Spring框架提供 对jdbc的进行了封装,可以操作 JdbcTemplate模板完成crud操作,JdbcT...

  • JDBC(二)

    前言 根据之前对JDBC的了解并使用之后,发现其中很多操作是可以进行封装的。所以接下来介绍一个自己封装的JDBC工...

  • 一.mysql批量操作

    一.配置 批量操作jdbc url需添加allowMultiQueries=true属性:实例:spring.da...

  • JdbcTemplate

    JdbcTemplate Spring为传统的jdbc API进行封装,简化持久层操作,虽然jdbcTemplat...

  • JAVAEE框架学习——Spring——整合JDBC aop中的

    Spring整合JDBC Spring中提供了一个可以操作数据库的对象,封装了JDBC技术 JDBCTemplat...

  • jfinal源码05:jdbc

    jfinal以插件的形式封装了jdbc 5.1 Model一个实例对应一张表 ActiveRecordPlugin...

  • Java web之JDBC

    一、JDBC的创建流程二、JDBC的封装三、用户操作和预处理块四、手动控制事务五、basedao实现更新(增删改)...

  • SpringBoot 整合jdbctemplate

    前言 JdbcTemplate简介 JdbcTemplate是Spring框架自带的对JDBC操作的封装,目的是提...

网友评论

      本文标题:JDBC操作封装实例

      本文链接:https://www.haomeiwen.com/subject/bhmsnxtx.html