创建PreparedStatement的正确方法是什么,重复使用几次,然后清理它?我使用以下模式:
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = getConnection(...);
// first use
stmt = conn.prepareStatement("some statement ?");
stmt.setString(1, "maybe some param");
if (stmt.execute()) {
...
}
// second use
stmt = conn.prepareStatement("some statement ?");
stmt.setString(1, "maybe some param");
if (stmt.execute()) {
...
}
// third use.
stmt = conn.prepareStatement("some statement");
stmt.execute();
}
finally {
if (stmt != null) {
try {
stmt.close();
} catch (Exception sqlex) {
sqlex.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (Exception sqlex) {
sqlex.printStackTrace();
}
conn = null;
}
}
我们可以像这样重用“stmt”对象,还是必须在每个查询之间调用stmt.close()?
由于
----------更新------------------------
啊,我明白了,我的每个陈述都会有所不同。那么这是一个更正确的模式吗?:
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = getConnection(...);
// first use
PreparedStatement stmt1 = null;
try {
stmt1 = conn.prepareStatement("some statement ?");
stmt1.setString(1, "maybe some param");
if (stmt1.execute()) {
...
}
}
finally {
if (stmt1 != null) {
try {
stmt1.close();
} catch (Exception ex) {}
}
}
// second use
PreparedStatement stmt2 = null;
try {
stmt2 = conn.prepareStatement("some different statement ?");
stmt2.setString(1, "maybe some param");
if (stmt2.execute()) {
...
}
}
finally {
if (stmt2 != null) {
try {
stmt2.close();
} catch (Exception ex) {}
}
}
// third use
PreparedStatement stmt3 = null;
try {
stmt3 = conn.prepareStatement("yet another statement ?");
stmt3.setString(1, "maybe some param");
if (stmt3.execute()) {
...
}
}
finally {
if (stmt3 != null) {
try {
stmt3.close();
} catch (Exception ex) {}
}
}
}
finally {
if (conn != null) {
try {
conn.close();
} catch (Exception sqlex) {
sqlex.printStackTrace();
}
conn = null;
}
}
因此,每个不同的语句将在下一个语句执行之前单独关闭。
答案 0 :(得分:5)
反过来说 - 你只需要准备一次,然后重复使用它。
即。这样:
// second use
stmt = conn.prepareStatement("some statement ?");
stmt.setString(1, "maybe some param");
if (stmt.execute()) {
...
}
应该成为这个:
// second use
stmt.setString(1, "maybe some param");
if (stmt.execute()) {
...
}
您的第三次使用,这是一个不同的声明,应该是一个新变量,或者首先关闭您准备好的声明。 (尽管通常使用PreparedStatements,你可以保留它们并重复使用它们。)