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