我遇到过这种模式。Connection当您需要执行多个 SQL 语句时,是否可以在单个方法中重用对象?
我最初的想法是在继续之前关闭所有资源:
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = ConnectionFactory.getConnection();
ps = conn.prepareStatement("SELECT * FROM MYTABLE WHERE COL=?");
ps.setString(1, "val");
rs = ps.executeQuery();
// get values used to determine the next statement type
} catch (SQLException e) {
LOG.error("SQL failed.", e);
} finally {
if(rs != null){rs.close();}
if(ps != null){ps.close();}
if(conn != null){conn.close();}
}
// Then another SQL statement is needed (either an UPDATE or INSERT).
// Repeat the same pattern to open, use and close the connection
执行以下操作是否同样安全?如果它是安全的,是否有真正的好处?
//... boilerplate
try {
conn = ConnectionFactory.getConnection();
ps = conn.prepareStatement("SELECT * FROM MYTABLE WHERE COL=?");
ps.setString(1, "val");
rs = ps.executeQuery();
// ... more
ps = conn.prepareStatement("UPDATE MYTABLE SET COL=?")
// ... etc
} finally {
if(rs != null){rs.close();}
if(ps != null){ps.close();}
if(conn != null){conn.close();}
}
弑天下
鸿蒙传说
相关分类