QueryRunner,节省步骤

增删改:

Connection conn=JDBCUtils.getCon();
String sql="insert into user(uname,pwd) values(?,?)";
QueryRunner qr=new QueryRunner();
int row=qr.update(conn,sql,user.getUname(),user.getPwd());
System.out.println(row);
conn.close();

查询操作:

四种常用方法:BeanHandler,BeanListHandler,ColumnListHandler,ScalarHandler

1. BeanHandler:将结果集中第一条记录封装到一个指定的javaBean中

String sql="select * from user";
QueryRunner qr=new QueryRunner(MyDBUtils.getDataSource());
User user=qr.query(sql,new BeanHandler<User>(User.class) );
System.out.println(user);
            

2.BeanListHandler:将结果集中每一条记录封装到指定的javaBean中,将这些javaBean在封装到List集合中

Connection conn=JDBCUtils.getCon();
String sql="select * from user where uid=?";
QueryRunner qr=new QueryRunner();
Object[] params = {1};
List<User> list=qr.query(conn, sql,new BeanListHandler<User>(User.class),params);
for(User user:list){
    System.out.println("get4:"+user);
}
conn.close();

3.ColumnListHandler:将结果集中指定的列的字段值,封装到一个List集合中

Connection conn=JDBCUtils.getCon();
        //String sql="select uname from user";
        String sql="select * from user";
        QueryRunner qr=new QueryRunner();
        //可在结果集中通过传参查询
        List<String> list=qr.query(conn,sql,new ColumnListHandler<String>("uname"));
        for(String s:list){
            System.out.println(s);
        }
        conn.close();

4.ScalarHandler:它是用于单数据。例如select count(*) from 表操作

Connection conn=JDBCUtils.getCon();
        String sql="select count(*) from user where uname=?";
        QueryRunner qr=new QueryRunner();
        //可在结果集中通过传参查询
        Long count=qr.query(conn,sql,new ScalarHandler<Long>(),"aaa");
        System.out.println("get6:"+count);
        conn.close();

DBCP连接池:

1.导入jar包

2.创建工具类

QueryRunner qr=new QueryRunner(MyDBUtils.getDataSource());

01-08 15:34