天天看点

Queryrunner类的使用

使用QueryRunner 类来执行sql语句的查询与操作

该类简单化了SQL查询,它与ResultSetHandler组合在一起使用可以完成大部分的数据库操作,能够大大减少编码量。

主要有三个方法:
   query()用于执行select
   update()用于执行inset/update/delete
   batch()批处理(不常用)
queryrunnet:提供了两个构造方法
   默认的构造方法
   需要一个 javax.sql.DataSource来作参数的构造方法。

BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中。
BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。
ScalarHandler:可以返回指定列的一个值或返回一个统计函数的值。
           

query主要有两种形式:

一般我们用C3P0来同意管理,QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource()));

query(sql,ResultSetHandler,Object…params);

query(conn,sql,ResultSetHandler,Object…params);

第一种不需要param

public int getCount() throws SQLException {
        QueryRunner run = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select count(*) from product";
        // 强制类型转换
        return ((Long) run.query(sql, new ScalarHandler())).intValue();

    }
           

第二种需要参数

public Product findProductByPid(String pid) throws SQLException {
        String sql = "select * from product where pid=?";
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        Product product = qr.query(sql,new BeanHandler<Product>(Product.class), pid);
        return product;
    }
           

第三种多个参数

public User login(User user) throws SQLException{
       QueryRunner runn=new QueryRunner(DataSourceUtils.getDataSource());
       String sql="select * from user where username=? and password=?";
       return runn.query(sql, new BeanHandler<User>(User.class),user.getUsername(),user.getPassword());
   }

           

BeanListHandler

public static List<Category> findAllCategories() throws SQLException{
        String sql = "select * from category";
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        return qr.query(sql, new BeanListHandler<Category>(Category.class));
    }