元数据和DbUtils

  使用元数据可以在jdbc中获取数据库的定义,例如:数据库、表、列的定义信息。

  在jdbc中可以使用: 数据库元数据、参数元数据、结果集元数据。

1.DataBaseMetaData对象

  Connection.getDatabaseMetaData()

getURL():返回一个String类对象,代表数据库的URL。

getUserName():返回连接当前数据库管理系统的用户名。

getDatabaseProductName():返回数据库的产品名称。

getDatabaseProductVersion():返回数据库的版本号。

getDriverName():返回驱动驱动程序的名称。

getDriverVersion():返回驱动程序的版本号。

isReadOnly():返回一个boolean值,指示数据库是否只允许读操作。

2.ParameterMetaData对象

  PreparedStatement . getParameterMetaData()

Select * from user where name=? And password=?

getParameterCount():获得指定参数的个数。

getParameterType(int param):获得指定参数的sql类型。

3.ResultSetMetaData对象

ResultSet. getMetaData()

getColumnCount():返回resultset对象的列数。

getColumnName(int column):获得指定列的名称。

getColumnTypeName(int column):获得指定列的类型。

4.使用元数据优化Dao

public class BaseDao{
    private Connection conn;
    private PreparedStatement stmt;
    private ResultSet resultSet;
    public void update(String sql,Object[] paramValues){
        conn = JdbcUtil.getConnection();
        try {
            stmt = conn.prepareStatement(sql);
            int parameterCount = stmt.getParameterMetaData()
                    .getParameterCount();
if(paramValues !=null&&paramValues.length>0){ for(int i = 0;i<parameterCount;i++) { stmt.setObject(i+1,paramValues[i]); } } stmt.executeUpdate(); } catch (Exception e) { throw new RuntimeException(e); }finally { JdbcUtil.close(conn,stmt); } } public <T> List<T> query(String sql,Object[] paramValues,Class<T> clazz){ try { List<T> list = new ArrayList<T>(); //要封装的对象 conn = JdbcUtil.getConnection(); stmt = conn.prepareStatement(sql); int count = stmt.getParameterMetaData().getParameterCount(); if(paramValues !=null&&paramValues.length>0){ for(int i = 0;i< count;i++) stmt.setObject(i+1,paramValues[i]); } resultSet = stmt.executeQuery(); ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); while(resultSet.next()){ T t = clazz.newInstance(); for(int i=0;i<columnCount;i++){ //获取列的名字 String columnName = metaData.getColumnName(i + 1); //获取列对应的值 Object object = resultSet.getObject(columnName); //设置到对象的属性中 BeanUtils.copyProperty(t,columnName,object); } //添加对象 list.add(t); } return list; }catch (Exception e){ throw new RuntimeException(e); }finally { JdbcUtil.close(conn,stmt); } } }

5.DbUtils组件

   commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影响程序的性能。因此dbutils成为很多不喜欢hibernate的公司的首选。

  在使用DbUtils组件时,bean的属性名要和表的列名一致(大小写不敏感),否则,封装为bean对象时,相应的属性会被设置为默认值。

6.DbUtils API

DbUtils   关闭资源、加载驱动

QueryRunner   组件的核心工具类:定义了所有的与数据库操作的方法(查询、更新),这些方法会自行处理 PreparedStatement 和 ResultSet 的创建和关闭。

Int  update(Connection conn, String sql, Object…  param)               执行更新带占位符的sql

Int[]  batch(Connection conn, String sql, Object[][] params)             批处理

T  query(Connection conn ,String sql, ResultSetHandler<T> rsh, Object... params)   查询方法

注意: 如果调用DbUtils组件的操作数据库方法,没有传入连接对象,那么在实例化QueryRunner对象的时候需要传入数据源对象: QueryRunner qr = new QueryRunner(ds);

Int  update( String sql, Object…  param);

Int[]  batch( String sql, Object[][] params)      

DbUtils提供的封装结果的一些对象:

1)BeanHandler: 查询返回单个对象

2)BeanListHandler: 查询返回list集合,集合元素是指定的对象

3)  ArrayHandler, 查询返回结果记录的第一行,封装对对象数组, 即返回:Object[]

4)  ArrayListHandler, 把查询的每一行都封装为对象数组,再添加到list集合中

5)  ScalarHandler 查询返回结果记录的第一行的第一列  (在聚合函数统计的时候用)

6)  MapHandler  查询返回结果的第一条记录封装为map

        conn = JdbcUtil.getConnection();    
        QueryRunner qr = new QueryRunner();
        //使用组件提供的结果集对象封装数据
        //封装单个对象
        String sql = "select *from student_info where stuId = ?";
        Student student = qr.query(conn, sql, new BeanHandler<Student>(Student.class),2008001);

        String sql = "select *from student_info";
        //返回封装为对象的list的结果集
        List<Student> students= qr.query(conn, sql, new BeanListHandler<Student>(Student.class));

        //返回结果集的第一个结果的数组
        Object[] query = qr.query(conn, sql, new ArrayHandler());

        //返回结果集所有结果组成的list
        List<Object[]> query = qr.query(conn, sql, new ArrayListHandler());

        //返回结果集的第一个结果的列名-列值的映射
        Map<String, Object> query = qr.query(conn, sql, new MapHandler());

        //返回结果集的第一行的第一列
        Long query = qr.query(conn, sql, new ScalarHandler<Long>());

 7.使用DbUtils优化Dao

public class AdminDao implements IAdminDao {

    private Connection con;
    private QueryRunner qr = new QueryRunner();

    @Override
    public Admin findByNameAndPwd(Admin admin) {
        String sql = "select * from admin where userName=? and pwd=?";
        try{
            con = JdbcUtil.getConnection();
            Admin ad = qr.query(con, sql, 
                    new BeanHandler<Admin>(Admin.class), 
                    admin.getUserName(),
                    admin.getPwd());
            return ad;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.closeAll(con, null, null);
        }
    }

    @Override
    public void save(Admin admin) {
        String sql = "INSERT INTO admin(userName,pwd) VALUES(?,?);";
        try {
            con = JdbcUtil.getConnection();
            // 使用DbUtils组件的方法更新
            qr.update(con, sql, admin.getUserName(),admin.getPwd());
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.closeAll(con, null, null);
        }
    }

    @Override
    public boolean userExists(String name) {
        String sql = "select id from admin where userName=?";
        try {
            con = JdbcUtil.getConnection();
            Integer in = qr.query(con, sql, new ScalarHandler<Integer>(), name);
            if (in != null){
                return true;
            }
            return false;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.closeAll(con, null, null);
        }
    }
}
原文地址:https://www.cnblogs.com/juaner767/p/5575613.html