queryrunner query怎么归还连接池

本文已收录于以下专栏:
相关文章推荐
首先用数据库连接池管理Connection,我们就可以重复使用Connection了,有了连接池我们就可以不用自己创建Connection,
然后用完把它归还给连接池就行了,首先用c3p0数据库连接...
1.数据库连接池什么是数据库连接池简单来说:数据库连接池就是提供连接的。为什么我们要使用数据库连接池
数据库的连接的建立和关闭是非常消耗资源的
频繁地打开、关闭连接造成系统性能低下
编写连接池
1. DButils工具类的介绍个三个核心类1. DButils工具类的介绍个三个核心类a: 概述
DBUtils是java编程中的数据库操作实用工具,小巧简单实用。
DBUtils封装了对JDBC的...
Tomcat内置连接池
 Tomcat服务器内置连接池 使用的是dbcp框架
 配置Tomcat内置连接池,通过JNDI方式 去访问Tomcat的内置连接池
JNDI Java命名和目录...
MySQL默认一个连接超过8小时无操作就断开该连接,对于想要长期保持连接的应用场景而言,太不方便
Python的MySQL绑定MySQLdb
发现DBUtils是一个不错的Python连接池 ...
1. c3p0数据库连接池
让我想起了星球大战里的C-3PO,哈哈。
1.1 数据库连接池的概念
用池来管理Connection,这可以重复使用Connection。有了池,所以我们就不用自己来...
DbUtils是基于c3p0来做的,功能很是强大。
首先做一个c3p0的连接池C3p0Pool:
package cn.hncu.c3p0;
import java.sql.Con...
使用第三方工具类创建连接池用到的jar包:
dbcp2 2.11
dbutils 1.6
logging 1.2
pool2 2.42
首先创建配置文件datasource.properties#必要...
他的最新文章
讲师:韦玮
讲师:陈守元
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)<span style="font-size:18 color:#:DBUtils中的QueryRunner的使用:
  1.1:QueryRunner中提供了对SQL语句操作的api;
  1.2:主要有三个方法:
    1.2.1:query():用于执行select(查询);
    1.2.2:update():用于执行insert(插入)/update(更新)/delete(删除);
    1.2.3:batch():批处理;
<span style="font-size:18 color:#:c3p0和QueryRunner的结合使用:
  2.1:首先导包,如下所示的包;
    c3p0-0.9.1.2.jar
    commons-dbutils-1.6.jar
    mysql-connector-java-5.1.12-bin.jar  
 & 2.2:当然导包之前你需要创建好数据库和数据表哦!~~~ 
    & 在src目录下面记住配置c3p0-config.xml文件
1 &c3p0-config&
&!-- c3p0默认配置,下面还可以配置多个数据库 --&
&default-config&
&property name=&jdbcUrl&&jdbc:mysql://localhost:3306/test
&/property&
&property name=&driverClass&&com.mysql.jdbc.Driver&/property&
&property name=&user&&root&/property&
&property name=&password&&123456&/property&
<span style="color:#
&property name=&initialPoolSize&&6&/property&
<span style="color:#
&property name=&maxPoolSize&&50&/property&
<span style="color:#
&property name=&maxIdleTime&&1000&/property&
<span style="color:#
&/default-config&
<span style="color:#
<span style="color:# &/c3p0-config&
 & 2.3:创建实体类,如User.java,源码如下,
1 package com.bie.
3 * @author BieHongLi
4 * @version 创建时间:日 下午12:55:21
7 public class User {
private int
<span style="color:#
<span style="color:#
<span style="color:#
<span style="color:#
<span style="color:#
public int getId() {
<span style="color:#
<span style="color:#
<span style="color:#
public void setId(int id) {
<span style="color:#
<span style="color:#
<span style="color:#
public String getName() {
<span style="color:#
<span style="color:#
<span style="color:#
public void setName(String name) {
<span style="color:#
this.name =
<span style="color:#
<span style="color:#
public String getPassword() {
<span style="color:#
<span style="color:#
<span style="color:#
public void setPassword(String password) {
<span style="color:#
this.password =
<span style="color:#
<span style="color:#
public String getEmail() {
<span style="color:#
<span style="color:#
<span style="color:#
public void setEmail(String email) {
<span style="color:#
this.email =
<span style="color:#
<span style="color:#
public String getPhone() {
<span style="color:#
<span style="color:#
<span style="color:#
public void setPhone(String phone) {
<span style="color:#
this.phone =
<span style="color:#
<span style="color:#
<span style="color:#
public String toString() {
<span style="color:#
return &User [, name=& &#43; name &#43; &, password=& &#43; password &#43; &, email=& &#43; email &#43; &, phone=& &#43; phone
<span style="color:#
&#43; &]&;
<span style="color:#
<span style="color:#
<span style="color:#
<span style="color:# }
  <span style="font-size:18 color:#.4:创建好实体类之后就可以根据MVC模式分层进行开发,这里只是模拟,所以创建dao层和servic层和test层。test层进行测试;
    所以先创建dao层进行创建接口,再创建实现接口的类,当然实现c3p0和QueryRunner的关键代码就是dao层哦,切记;
    当然了还有工具类utils层提取的公共的方法;
1 package com.bie.
3 import java.util.L
5 import com.bie.po.U
8 * @author BieHongLi
9 * @version 创建时间:日 下午5:46:38
<span style="color:# *
<span style="color:# */
<span style="color:# public interface UserDao {
<span style="color:#
<span style="color:#
<span style="color:#
* 查询所有的用户信息
<span style="color:#
<span style="color:#
<span style="color:#
public List&User& selectUser();
<span style="color:#
<span style="color:#
<span style="color:#
* 根据编号查询
<span style="color:#
* @param id
<span style="color:#
<span style="color:#
<span style="color:#
public User selectUserId(int id);
<span style="color:#
<span style="color:#
<span style="color:#
<span style="color:#
* 根据条件查询信息
<span style="color:#
* @param user
<span style="color:#
<span style="color:#
<span style="color:#
public List&User& select(String sql,List&Object& list);
<span style="color:#
<span style="color:#
<span style="color:# }
1 package com.bie.dao.
3 import java.util.L
5 import mons.dbutils.QueryR
6 import mons.dbutils.handlers.BeanH
7 import mons.dbutils.handlers.BeanListH
9 import com.bie.dao.UserD
<span style="color:# import com.bie.po.U
<span style="color:# import com.bie.util.BaseU
<span style="color:#
<span style="color:# /**
<span style="color:# * @author BieHongLi
<span style="color:# * @version 创建时间:日 下午5:47:35
<span style="color:# *
<span style="color:# */
<span style="color:# public class UserDaoImpl implements UserDao{
<span style="color:#
<span style="color:#
<span style="color:#
public List&User& selectUser() {
<span style="color:#
//创建QueryRunner
<span style="color:#
//记住查询是BeanListHandler区别增删改的方法BeanHandler
<span style="color:#
QueryRunner qr=BaseUtils.getQueryRunner();
<span style="color:#
<span style="color:#
String sql=&select * from user &;
<span style="color:#
//这句话就相当于之前写的下面这一长串代码,这就是QueryRunner的方便之处
<span style="color:#
<span style="color:#
*User user=new User();
<span style="color:#
user.setId(rs.getInt(&id&));
<span style="color:#
user.setName(rs.getString(&name&));
<span style="color:#
user.setPassword(rs.getString(&password&));
<span style="color:#
user.setEmail(rs.getString(&email&));
<span style="color:#
user.setPhone(rs.getString(&phone&));
<span style="color:#
<span style="color:#
return qr.query(sql, new BeanListHandler&User&(User.class));
<span style="color:#
<span style="color:#
} catch (Exception e) {
<span style="color:#
e.printStackTrace();
<span style="color:#
<span style="color:#
return null;
<span style="color:#
<span style="color:#
<span style="color:#
<span style="color:#
public User selectUserId(int id) {
<span style="color:#
//创建QueryRunner
<span style="color:#
QueryRunner qr=BaseUtils.getQueryRunner();
<span style="color:#
String sql=&select * from user where id=? &;
<span style="color:#
<span style="color:#
//使用QueryRunner的强大之处在于此处。
<span style="color:#
return qr.query(sql,new BeanHandler&User&(User.class), id);
<span style="color:#
} catch (Exception e) {
<span style="color:#
e.printStackTrace();
<span style="color:#
<span style="color:#
return null;
<span style="color:#
<span style="color:#
<span style="color:#
<span style="color:#
public List&User& select(String sql,List&Object& list) {
<span style="color:#
//创建QueryRunner
<span style="color:#
QueryRunner qr=BaseUtils.getQueryRunner();
<span style="color:#
<span style="color:#
//第一个参数是传来的sql,第二个是实现实体类的设置,第三个是集合转化为数组
<span style="color:#
return qr.query(sql, new BeanListHandler&User&(User.class), list.toArray());
<span style="color:#
<span style="color:#
} catch (Exception e) {
<span style="color:#
e.printStackTrace();
<span style="color:#
<span style="color:#
return null;
<span style="color:#
<span style="color:#
<span style="color:#
<span style="color:# }
  这里将BaseUtils类写到这里,因为这个也是c3p0和QueryRunner的核心啊!!!
1 package com.bie.
3 import java.sql.SQLE
4 import java.util.L
6 import javax.sql.DataS
8 import mons.dbutils.QueryR
<span style="color:# import com.mchange.boPooledDataS
<span style="color:#
<span style="color:# /**
<span style="color:# * @author BieHongLi
<span style="color:# * @version 创建时间:日 下午1:29:50
<span style="color:# * 数据库连接工具类
<span style="color:# */
<span style="color:# public class BaseUtils {
<span style="color:#
<span style="color:#
//初始化c3p0
<span style="color:#
private static DataSource dataSource=null;
<span style="color:#
<span style="color:#
<span style="color:#
//自动加载src目录下面的c3p0的配置文件,【c3p0-config.xml】
<span style="color:#
dataSource = new ComboPooledDataSource();
<span style="color:#
<span style="color:#
<span style="color:#
public static QueryRunner getQueryRunner(){
<span style="color:#
//第一步:创建QueryRunner对象,传入连接池对象
<span style="color:#
//在创建QueryRunner对象的时候,如果传入数据对象dataSource,
<span style="color:#
//那么在使用QueryRunner对象的方法时候,就不需要传入连接对象
<span style="color:#
QueryRunner query=new QueryRunner(dataSource);
<span style="color:#
//第二步:会自动从数据源中获取连接(不用关闭连接)
<span style="color:#
<span style="color:#
<span style="color:#
<span style="color:#
<span style="color:#
* 实现增删改的公共方法
<span style="color:#
* @param sql
<span style="color:#
* @param arr
<span style="color:#
<span style="color:#
<span style="color:#
public static boolean addUpdateDelete(String sql,Object[] arr){
<span style="color:#
QueryRunner qr=getQueryRunner();
<span style="color:#
<span style="color:#
<span style="color:#
count = qr.update(sql, arr);
<span style="color:#
if(count&0){
<span style="color:#
return true;
<span style="color:#
<span style="color:#
return false;
<span style="color:#
<span style="color:#
} catch (SQLException e) {
<span style="color:#
e.printStackTrace();
<span style="color:#
<span style="color:#
return false;
<span style="color:#
<span style="color:#
<span style="color:# }
  <span style="font-size:18 color:#.5:完成dao层和BaseUtils层之后可以直接在service层进行增删改,dao层就不用写了;
1 package com.bie.
3 import java.util.L
5 import com.bie.po.U
8 * @author BieHongLi
9 * @version 创建时间:日 下午7:10:32
<span style="color:# *
<span style="color:# */
<span style="color:# public interface UserService {
<span style="color:#
<span style="color:#
<span style="color:#
* 根据条件查询用户信息
<span style="color:#
* @param user
<span style="color:#
<span style="color:#
<span style="color:#
public List&User& select(User user);
<span style="color:#
<span style="color:#
<span style="color:#
* 添加用户信息
<span style="color:#
* @param user
<span style="color:#
<span style="color:#
<span style="color:#
public boolean insertUser(User user);
<span style="color:#
<span style="color:#
<span style="color:#
* 修改用户的信息
<span style="color:#
* @param user
<span style="color:#
<span style="color:#
<span style="color:#
public boolean updateUser(User user);
<span style="color:#
<span style="color:#
<span style="color:#
* 删除用户信息
<span style="color:#
* @param id
<span style="color:#
<span style="color:#
<span style="color:#
public boolean deleteUser(int id);
<span style="color:# }
1 package com.bie.service.
3 import java.util.ArrayL
4 import java.util.L
6 import com.bie.dao.UserD
7 import com.bie.dao.impl.UserDaoI
8 import com.bie.po.U
9 import com.bie.service.UserS
10 import com.bie.util.BaseU
13 * @author BieHongLi
14 * @version 创建时间:日 下午7:10:48
17 public class UserServiceImpl implements UserService{
private UserDao dao=new UserDaoImpl();
public List&User& select(User user) {
StringBuilder sql=new StringBuilder(&select * from user where 1=1 &);
List&Object& list=new ArrayList&Object&();
if(user!=null){
//根据编号查询
if(user.getId()!=0 && !&&.equals(user.getId())){
sql.append(& and id = ? &);
list.add(user.getId());
//根据名称模糊查询,模糊查询&& %% && &#43;&#43;
if(user.getName()!=null && !&&.equals(user.getName())){
sql.append(& and name like ? &);
list.add(&%&&#43;user.getName()&#43;&%&);
return dao.select(sql.toString(), list);
public boolean insertUser(User user) {
String sql=&insert into user values(0,?,?,?,?)&;
List&Object& list=new ArrayList&&();
if(user!=null){
list.add(user.getName());
list.add(user.getPassword());
list.add(user.getEmail());
list.add(user.getPhone());
return BaseUtils.addUpdateDelete(sql, list.toArray());
} catch (Exception e) {
e.printStackTrace();
return false;
public boolean updateUser(User user) {
String sql=&update user set name=?,password=?,email=?,phone=? where id=? &;
List&Object& list=new ArrayList&&();
if(user!=null){
list.add(user.getName());
list.add(user.getPassword());
list.add(user.getEmail());
list.add(user.getPhone());
//根据编号修改信息
list.add(user.getId());
return BaseUtils.addUpdateDelete(sql, list.toArray());
} catch (Exception e) {
e.printStackTrace();
return false;
public boolean deleteUser(int id) {
String sql=&delete from user where id=? &;
List&Object& list=new ArrayList&&();
if(id!=0){
//根据编号修改信息
list.add(id);
return BaseUtils.addUpdateDelete(sql, list.toArray());
} catch (Exception e) {
e.printStackTrace();
return false;
<span style="color:#0 }
  2.6:使用junit测试,完成使用c3p0和QueryRunner的练习;
1 package com.bie.
3 import java.util.L
5 import org.junit.T
7 import com.bie.dao.UserD
8 import com.bie.dao.impl.UserDaoI
9 import com.bie.po.U
<span style="color:# import com.bie.service.UserS
<span style="color:# import com.bie.service.impl.UserServiceI
<span style="color:#
<span style="color:# /**
<span style="color:# * @author BieHongLi
<span style="color:# * @version 创建时间:日 下午5:57:25
<span style="color:# *
<span style="color:# */
<span style="color:# public class QueryRunnerTest {
<span style="color:#
<span style="color:#
private UserDao dao=new UserDaoImpl();
<span style="color:#
private UserService service=new UserServiceImpl();
<span style="color:#
<span style="color:#
//查询所有信息的测试
<span style="color:#
<span style="color:#
public void selectUser(){
<span style="color:#
List&User& list=dao.selectUser();
<span style="color:#
for(User u:list){
<span style="color:#
System.out.println(u);
<span style="color:#
<span style="color:#
<span style="color:#
<span style="color:#
//根绝id查询的信息
<span style="color:#
<span style="color:#
public void selectUserId(){
<span style="color:#
User user=dao.selectUserId(1);
<span style="color:#
System.out.println(user);
<span style="color:#
<span style="color:#
<span style="color:#
//根据条件查询信息
<span style="color:#
<span style="color:#
public void select(){
<span style="color:#
User user=new User();
<span style="color:#
user.setName(&张三&);
<span style="color:#
List&User& list=service.select(user);
<span style="color:#
for(User u:list){
<span style="color:#
System.out.println(u);
<span style="color:#
<span style="color:#
<span style="color:#
<span style="color:#
<span style="color:#
public void insertUser(){
<span style="color:#
User user=new User();
<span style="color:#
user.setName(&张三&);
<span style="color:#
user.setPassword(&123456&);
<span style="color:#
user.setEmail(&&);
<span style="color:#
user.setPhone(&11223&);
<span style="color:#
<span style="color:#
boolean mark=service.insertUser(user);
<span style="color:#
<span style="color:#
System.out.println(&插入成功&);
<span style="color:#
<span style="color:#
System.out.println(&插入失败&);
<span style="color:#
<span style="color:#
<span style="color:#
<span style="color:#
<span style="color:#
<span style="color:#
public void update(){
<span style="color:#
User user=new User();
<span style="color:#
user.setName(&李四&);
<span style="color:#
user.setId(1);
<span style="color:#
<span style="color:#
boolean mark=service.updateUser(user);
<span style="color:#
<span style="color:#
System.out.println(&修改成功&);
<span style="color:#
<span style="color:#
System.out.println(&修改失败&);
<span style="color:#
<span style="color:#
<span style="color:#
<span style="color:#
<span style="color:#
public void delete(){
<span style="color:#
boolean mark=service.deleteUser(1);
<span style="color:#
<span style="color:#
System.out.println(&用户信息删除成功&);
<span style="color:#
<span style="color:#
System.out.println(&用户信息删除失败&);
<span style="color:#
<span style="color:#
<span style="color:#
<span style="color:# }
演示效果如下所示:
初试成功,等待复试(技术试),加油!!!奋斗吧,小青年
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:32792次
排名:千里之外
原创:34篇
转载:157篇
评论:10条
(151)(19)(16)(5)
(window.slotbydup = window.slotbydup || []).push({
id: '4740887',
container: s,
size: '250,250',
display: 'inlay-fix'前言:[本文属于原创分享文章, 转载请注明出处, 谢谢.]前面已经有文章说了DBUtils的一些特性, 这里再来详细说下QueryRunner的一些内部实现, 写的有错误的地方还恳请大家指出.&
QueryRunner类
QueryRunner中提供对语句操作的它主要有三个方法  query() 用于执行  update() 用于执行  batch() 批处理1,Query语句先来看下query的两种形式, 我们这里主要讲第一个方法, 因为我们用C3P0来统一管理connection.(QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource()))query(sql,ResultSetHandler,Object...params);query(conn,sql,ResultSetHandler,Object...params);
第一种: 不需要params
//查询所有图书
public List&Book& selectAllBooks() throws SQLException {
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
return qr.query("select * from books", new BeanListHandler&Book&(Book.class));
第二种: 需要一个参数查询
//根据id查询指定的书
public Book selectBookById(String id) throws SQLException {
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
return qr.query("select * from books where id=?", new BeanHandler(Book.class),id);
第三种:需要多个参数查询
//多条件查询图书信息
public List&Book& findBookByManyCondition(String id, String category,
String name, String minprice, String maxprice) throws SQLException {
StringBuilder sql = new StringBuilder("select * from books where 1=1");
List list = new ArrayList();
if(!"".equals(id)){
sql.append(" and id like ?");
list.add("%"+id+"%");
if(!"".equals(category)){
sql.append(" and category=?");
list.add(category);
if(!"".equals(name)){
sql.append(" and name like ?");
list.add("%"+name+"%");
if(!"".equals(minprice)){
sql.append(" and price & ?");
list.add(minprice);
if(!"".equals(maxprice)){
sql.append(" and price & ?");
list.add(maxprice);
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
return qr.query(sql.toString(),new BeanListHandler&Book&(Book.class),list.toArray());
那么我们来看下源码的实现:&(1)QueryRunner.java
//第一种情况,无参数
public &T& T query(String sql, ResultSetHandler&T& rsh) throws SQLException {
Connection conn = this.prepareConnection();
return this.query(conn, true, sql, rsh, (Object[]) null);
//第二种和第三种使用同一方法: 需要参数
public &T& T query(String sql, ResultSetHandler&T& rsh, Object... params) throws SQLException {
Connection conn = this.prepareConnection();
return this.query(conn, true, sql, rsh, params);
解读: 这里先是获取connection, 利用this.preparaConnection() 获取. 然后调用query()方法去执行查询语句. 接下来看源码是如何获取到当前传输过来的connection以及query()方法的内部实现.
protected Connection prepareConnection() throws SQLException {
if (this.getDataSource() == null) {
throw new SQLException("QueryRunner requires a DataSource to be " +
"invoked in this way, or a Connection should be passed in");
return this.getDataSource().getConnection();
这里很简单, 因为我们用的C3P0数据库连接池获取的DataSource, 所以这里直就可以过去到当前的Connection.接下来就看下query()方法的内部实现.&
private &T& T query(Connection conn, boolean closeConn, String sql, ResultSetHandler&T& rsh, Object... params)
throws SQLException {
if (conn == null) {
throw new SQLException("Null connection");
if (sql == null) {
if (closeConn) {
close(conn);
throw new SQLException("Null SQL statement");
if (rsh == null) {
if (closeConn) {
close(conn);
throw new SQLException("Null ResultSetHandler");
PreparedStatement stmt = null;
ResultSet rs = null;
T result = null;
stmt = this.prepareStatement(conn, sql);
this.fillStatement(stmt, params);
rs = this.wrap(stmt.executeQuery());
result = rsh.handle(rs);
} catch (SQLException e) {
this.rethrow(e, sql, params);
} finally {
close(rs);
} finally {
close(stmt);
if (closeConn) {
close(conn);
解读: 在这里可以看出, 无论是否有传递参数params, 都调用的是同一个query方法, 接着来看this.fillStatement(stmt, params);是如何将参数赋予preparedStatement中的.&
public void fillStatement(PreparedStatement stmt, Object... params) throws SQLException {
// check the parameter count, if we can
ParameterMetaData pmd = null;
if (!pmdKnownBroken) {
pmd = stmt.getParameterMetaData();
int stmtCount = pmd.getParameterCount();
int paramsCount = params == null ? 0 : params.
if (stmtCount != paramsCount) {
throw new SQLException("Wrong number of parameters: expected "
+ stmtCount + ", was given " + paramsCount);
// nothing to do here
if (params == null) {
for (int i = 0; i & params. i++) {
if (params[i] != null) {
stmt.setObject(i + 1, params[i]);
// VARCHAR works with many drivers regardless
// of the actual column type.
Oddly, NULL and
// OTHER don't work with Oracle's drivers.
int sqlType = Types.VARCHAR;
if (!pmdKnownBroken) {
sqlType = pmd.getParameterType(i + 1);
} catch (SQLException e) {
pmdKnownBroken = true;
stmt.setNull(i + 1, sqlType);
这个方法就是核心所在. 第一种情况: 当params为null的时候, 直接return然后执行sql语句.第二种第三种情况: 当params不为null时, 循环遍历传入的params, 然后将params赋值到preparedStatement中, 然后填充占位符进行sql查询. 这里我们也来回顾下直接使用preparedStatement来进行查询的方式:
public void update(){
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
conn = JdbcUtils.getConnection();
String sql = "update users set name=?,email=? where id=?";
st = conn.prepareStatement(sql);
st.setString(1, "gacl");
st.setString(2, "");
st.setInt(3, 2);
int num = st.executeUpdate();
if(num&0){
System.out.println("更新成功!!");
}catch (Exception e) {
e.printStackTrace();
JdbcUtils.release(conn, st, rs);
public void find(){
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
conn = JdbcUtils.getConnection();
String sql = "select * from users where id=?";
st = conn.prepareStatement(sql);
st.setInt(1, 1);
rs = st.executeQuery();
if(rs.next()){
System.out.println(rs.getString("name"));
}catch (Exception e) {
JdbcUtils.release(conn, st, rs);
2, Update语句查看update语句:
//修改图书
public void updateBook(Book book) throws SQLException {
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
qr.update(
"UPDATE books SET NAME=? ,price=?,bnum=?,category=?,description=? WHERE id=?",
book.getName(), book.getPrice(), book.getBnum(),
book.getCategory(), book.getDescription(), book.getId())
接着是QueryRunner.java中的update 方法:
public int update(String sql, Object... params) throws SQLException {
Connection conn = this.prepareConnection();
return this.update(conn, true, sql, params);
private int update(Connection conn, boolean closeConn, String sql, Object... params) throws SQLException {
if (conn == null) {
throw new SQLException("Null connection");
if (sql == null) {
if (closeConn) {
close(conn);
throw new SQLException("Null SQL statement");
PreparedStatement stmt = null;
int rows = 0;
stmt = this.prepareStatement(conn, sql);
this.fillStatement(stmt, params);
rows = stmt.executeUpdate();
} catch (SQLException e) {
this.rethrow(e, sql, params);
} finally {
close(stmt);
if (closeConn) {
close(conn);
到了参数赋值的时候又调用了上面的fillStatement方法, 这里就不再阐述了.&3, Batch语句这里直接看batch方法的实例, 然后结合源码的实现.
//批量删除
public void delBooks(String[] ids) throws SQLException {
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
Object[][] params = new Object[ids.length][];//高维确定执行sql语句的次数,低维是给?赋值
for (int i = 0; i & params. i++) {
params[i] = new Object[]{ids[i]};//给&?&赋值
qr.batch("delete from books where id=?", params);
然后看QueryRunner中的batch()方法:
public int[] batch(String sql, Object[][] params) throws SQLException {
Connection conn = this.prepareConnection();
return this.batch(conn, true, sql, params);
private int[] batch(Connection conn, boolean closeConn, String sql, Object[][] params) throws SQLException {
if (conn == null) {
throw new SQLException("Null connection");
if (sql == null) {
if (closeConn) {
close(conn);
throw new SQLException("Null SQL statement");
if (params == null) {
if (closeConn) {
close(conn);
throw new SQLException("Null parameters. If parameters aren't need, pass an empty array.");
PreparedStatement stmt = null;
int[] rows = null;
stmt = this.prepareStatement(conn, sql);
for (int i = 0; i & params. i++) {
this.fillStatement(stmt, params[i]);
stmt.addBatch();
rows = stmt.executeBatch();
} catch (SQLException e) {
this.rethrow(e, sql, (Object[])params);
} finally {
close(stmt);
if (closeConn) {
close(conn);
解读: 因为params是一个二维数组, 所以往preparedStatement中赋值的时候使用了for循环, 然后通过preparedstatement.addBatch() 进行批量添加, 然后执行executeBatch()进行操作.
* Adds a set of parameters to this &code&PreparedStatement&/code&
* object's batch of commands.
* @exception SQLException if a database access error occurs or
* this method is called on a closed &code&PreparedStatement&/code&
* @see Statement#addBatch
* @since 1.2
void addBatch() throws SQLE
一看时间这么晚了, QueryRunner暂时就这么多了, 关于QueryRunner的用法自己挖掘的还不够透彻, 写在这里当做记录和交流. .
阅读(...) 评论()}

我要回帖

更多关于 queryrunner insert 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信