commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影响程序的性能。因此dbutils成为很多不喜欢hibernate的公司的首选。
/** * DbUtils的用法:利用DbUtils实现增删改查操作 * @project_name Day12 * @class_name DbUtilsDemo1 * @author Dovinya * @data 2014-8-27 下午11:07:09 * @version 1 * @notes */ /* create database day12; use day12; create table table1 ( id int primary key auto_increment, name varchar(20), salary double ); insert into table1 values(null,'zhang',234.5); insert into table1 values(null,'li',234.5); insert into table1 values(null,'wang',3242); insert into table1 values(null,'zhao',32543); insert into table1 values(null,'pan',4654); insert into table1 values(null,'he',4235); * */ public class DbUtilsDemo1 { /* * 利用DbUtils实现更改操作 */ public void update() throws SQLException { //获取数据源对象 QueryRunner runner = new QueryRunner(new ComboPooledDataSource()); runner.update("update table1 set salary =100"); } @Test public void add() throws SQLException{ //获取数据源对象 QueryRunner runner = new QueryRunner(new ComboPooledDataSource()); runner.update("insert into table1 values(1,?,?)","lisi",1000); } @Test public void delete() throws SQLException{ //获取数据源对象 QueryRunner runner = new QueryRunner(new ComboPooledDataSource()); runner.update("delete from table1 where name = 'lisi'"); } @Test public void query() throws SQLException{ //获取数据源对象 QueryRunner runner = new QueryRunner(new ComboPooledDataSource()); List<User> list = runner.query("select *from table1 where id<?", new ResultSetHandler<List<User>>(){ @Override public List<User> handle(ResultSet rs) throws SQLException { List<User> list = new ArrayList<User>(); while(rs.next()){ User user = new User(); user.setId(rs.getInt("id")); user.setName(rs.getString("name")); user.setSalary(rs.getDouble("salary")); list.add(user); } return list; } }, 5); System.out.println(list); //这里可以加断点调试观察 } }