Geo*_*f L 2 java jdbc prepared-statement
我知道,如果您创建 SQLPreparedStatement 或 ResultSet,则应在完成后对资源使用 .close() 。但是,如果我正在循环并在每次迭代中重新创建PreparedStatement,那么我是否仍然需要在每次迭代期间或在完成时对其调用 .close() ?
例如,如果我有这个:
private Connection con;
private String[] queries;
private PreparedStatement stmt;
...
create connection
fill array queries with 10 queries in it
...
for (int i = 0; i < 10; i++) {
stmt = con.prepareStatement(queries[i], Statement.RETURN_GENERATED_KEYS);
stmt.executeUpdate();
// necessary?
stmt.close()
}
Run Code Online (Sandbox Code Playgroud)
每次迭代是否有必要 .close() stmt ,还是应该在循环完成时执行此操作?为什么或者为什么不?谢谢。
你\xe2\x80\x99在每次迭代中创建一个新对象。您保持打开状态的每个语句都会使数据库服务器上的资源保持打开状态的时间超过必要的时间。关闭连接应该会清理所有内容,但众所周知 JDBC 驱动程序存在无法清理的错误。
\n将它们全部关闭在finally块中,或者对资源使用try。
\n