美文网首页java学习路Java学习笔记Java 杂谈
[原创]关于DBUtils用完之后关闭连接对象

[原创]关于DBUtils用完之后关闭连接对象

作者: H_Man | 来源:发表于2016-09-18 10:08 被阅读1919次

今天早上在写代码时忽然想起昨天写的关于DBUtils的问题,思考到似乎没有关闭连接这个功能,特地去官网查询了一下 得到以下代码:

创建QueryRunner时传入对象是dataSource的

// Create a QueryRunner that will use connections from// the given DataSourceQueryRunnerrun=newQueryRunner(dataSource);

// Execute the query and get the results back from the handler

Object[]result=run.query("SELECT * FROM Person WHERE name=?",h,"John Doe");

创建QR对象时没有传入参数

Notice that you are responsible for closing the Connection in this example

注意,在这个示例中,您将负责关闭连接

ResultSetHandler h = ... // Define a handler the same as above example

// No DataSource so we must handle Connections manually

QueryRunner run = new QueryRunner();

Connection conn = ... // open a connection

try{

Object[] result = run.query(

conn, "SELECT*FROMPersonWHEREname=?", h, "John Doe");

// do something with the result

} finally {

// Use this helper method so we don't have to check for null

//这时需要我们手动来关闭

DbUtils.close(conn);

}

得出结论,DBUtils在创建QueryRunner时传入dataSource对象每次在执行完之后都会自动关闭Connection连接对象~所以再也不用担心没有关闭对象而导致的问题了~

如果没有传入dataSource的话  需要手动关闭

相关文章

网友评论

  • 代帅卿:我也使用了Dbutils,遇到Connection没有释放的问题,看了一下源码,确实有close的代码,但是测试了一下,connection并没有被自动关闭,还是需要自己手动关闭。
    H_Man:@代帅卿 确实,我没有写周全,互粉一下,以后多多指教
    代帅卿:@暴躁的黄子涵丶 我测试的是传Connection的,传Connection需要手动关闭连接,如果你传的是DataSource就不要了,Dutils是会给自动关闭的,因为我的项目中需要自己处理事务,所以需要传Connection,官方文档有解释http://commons.apache.org/proper/commons-dbutils/examples.html这是链接,里面这句话You could also perform the previous query using a java.sql.Connection object instead of a DataSource. Notice that you are responsible for closing the Connection in this example.作了解释
    H_Man:@代帅卿 确定是吗?能不能让我看一下你的测试代码
  • 嘹亮的浩哥:markdown。。。。
  • George_Antonio:几篇文章让我捡起了连接池,感觉作者挺细心负责的,赞一个
    H_Man: @暴走的猛士 么么哒

本文标题:[原创]关于DBUtils用完之后关闭连接对象

本文链接:https://www.haomeiwen.com/subject/tbwwettx.html