DBUtils封装了对JDBC的操作,简化了JDBC操作,可以少写代码
两个类
QueryRunner中提供对sql语句操作的API.
ResultSetHandler接口,用于定义select操作后,怎样封装结果集.
QueryRunner核心类
l update(Connection conn, String sql, Object... params) ,用来完成表数据的增加、删除、更新操作
l query(Connection conn, String sql, ResultSetHandler<T> rsh, Object... params) ,用来完成表数据的查询操作
增加
//获取一个用来执行SQL语句的对象 QueryRunner
QueryRunner qr = new QueryRunner();
String sql = "INSERT INTO zhangwu(name,money,parent) VALUES(?,?,?)";
Object[] params = {"股票收入", 5500, "收入"};
Connection conn = JDBCUtils.getConnection();
int line = qr.update(conn,sql,params);// 用来完成表数据的增加、删除、更新操作
//结果集处理
System.out.println("line = " + line);
删除
//创建一个QueryRunner对象,用来完成SQL语句的执行
QueryRunner qr = new QueryRunner();
//执行SQL语句
String sql = "DELETE FROM zhangwu WHERE name = ?";
Object[] params = {"股票收入"};
Connection conn = JDBCUtils.getConnection();
int line = qr.update(conn, sql, params);
//结果集的处理
System.out.println("line="+line);
ResultSetHandler结果集处理类
查询
Object[] ArrayHandler------查询一条
List<Object[]> ArrayListHandler------查询
BeanHandler()
BeanListHandler() ----封装类的内容(所有)
//获取QueryRunner
QueryRunner qr = new QueryRunner();
//执行SQL语句
String sql = "SELECT * FROM zhangwu WHERE id=?";
Object[] params = {1};
Connection conn = JDBCUtils.getConnection();
ZhangWu zw = qr.query(conn, sql, new BeanHandler<ZhangWu>(ZhangWu.class), params);
//结果集处理
System.out.println(zw);
conn.close();
//获取QueryRunner
QueryRunner qr = new QueryRunner();
//执行SQL语句
String sql = "SELECT * FROM zhangwu WHERE money>?";
Object[] params = {2000};
Connection conn = JDBCUtils.getConnection();
List<ZhangWu> list = qr.query(conn, sql, new BeanListHandler<ZhangWu>(ZhangWu.class), params);
ColumnListHandler ----取一列的数据
ScalarHandler查询-------它是用于单数据。例如select count(*) from 表操作。
//获取QueryRunner对象
QueryRunner qr = new QueryRunner();
//执行SQL语句
String sql = "SELECT name FROM zhangwu WHERE money>?";
Object[] params = {2000};
Connection conn = JDBCUtils.getConnection();
List<String> list = qr.query(conn, sql, new ColumnListHandler<String>(), params);
//结果集的处理
for (String str : list) {
System.out.println(str);
}
conn.close();
//获取QueryRunner对象
QueryRunner qr = new QueryRunner();
//执行SQL语句
String sql = "SELECT MAX(money) FROM zhangwu";
Object[] params = {};
Connection conn = JDBCUtils.getConnection();
Double max = qr.query(conn, sql, new ScalarHandler<Double>(), params);
//结果集的处理
System.out.println("max=" + max);
conn.close();