今天早上在寫代碼時忽然想起昨天寫的關(guān)于DBUtils的問題,思考到似乎沒有關(guān)閉連接這個功能,特地去官網(wǎng)查詢了一下 得到以下代碼:
創(chuàng)建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");
創(chuàng)建QR對象時沒有傳入?yún)?shù)
Notice that you are responsible for closing the Connection in this example
注意舶斧,在這個示例中欣鳖,您將負責關(guān)閉連接
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
//這時需要我們手動來關(guān)閉
DbUtils.close(conn);
}
得出結(jié)論,DBUtils在創(chuàng)建QueryRunner時傳入dataSource對象每次在執(zhí)行完之后都會自動關(guān)閉Connection連接對象~所以再也不用擔心沒有關(guān)閉對象而導致的問題了~
如果沒有傳入dataSource的話? 需要手動關(guān)閉