上一次介绍了一下DbUtils组件的基本用法,其中最值得关注的就是QueryRunner对象,这应该是整个DbUtils组件最重要的一个组件,因此下面将详细的介绍其功能。
DbUtils的方法并不多,除前面已经介绍的query对象外,还有两个比较重要的方法,分别是fillStatement与 batch方法,可以看出这两个方法都与Statement相关。
batch方法的参数形式为:
- batch(String sql, Object[][] params)
上面的方法执行一个批处理操作,其中params表示参数替换的数组,下面给出其简单用法:
- ...................
- @Test
- public void testBatch() throws SQLException{
- String sql = "insert user(name,password) values(?,?)";
- QueryRunner query = new QueryRunner(ConnectionPool.getDataSource());
- String[][] params = {{"fans","2008"},{"fansof","2009"}};
- query.batch(sql, params);
- }
- ...............
至于fillStatement系列的方法可能稍微麻烦一点,它有以下几种形式:
- fillStatement(PreparedStatement stmt, Object[] params)
- fillStatementWithBean(PreparedStatement stmt, Object bean, PropertyDescriptor[] properties)
- fillStatementWithBean(PreparedStatement stmt, Object bean, String[] propertyNames)
以上几种方式中第一种与第三种比较有用,第二种是底层实现,一般不会直接使用。
第一种用法最简单,直接将参数填充即可:
- ...........
- @Test
- public void testInsertWithStatementBatch() throws SQLException{
- String sql = "insert user(name,password) values(?,?)";
- QueryRunner query = new QueryRunner(ConnectionPool.getDataSource());
- PreparedStatement ps = ConnectionPool.getConnection().prepareStatement(sql);
- String[] param = {"fanso","2008"};
- String[] param2 = {"fansp","2008"};
- query.fillStatement(ps, param);
- ps.addBatch();
- query.fillStatement(ps, param2);
- ps.addBatch();
- ps.executeBatch();
- }
- ...........
如果客户端传过来的是Java对象的话,上面的方法就不太好了,于是可以用上面的第三种参数形式:
- ..........
- @Test
- public void testInsertWithBeanBatch() throws SQLException, IntrospectionException{
- String sql = "insert user(name,password) values(?,?)";
- QueryRunner query = new QueryRunner(ConnectionPool.getDataSource());
- PreparedStatement ps = ConnectionPool.getConnection().prepareStatement(sql);
- User user = new User();
- user.setName("fansofjava");
- user.setPassword("2012");
- User user2 = new User();
- user2.setName("fansofjava");
- user2.setPassword("2013");
- String[] propertyName = {"name","password"};
- query.fillStatementWithBean(ps, user, propertyName);
- ps.addBatch();
- query.fillStatementWithBean(ps, user2, propertyName);
- ps.addBatch();
- ps.executeBatch();
- }
- ........
关于QueryRunner的用法基本上讲完了,能掌握这些,我想基本就够了。