我如何关闭().executeUpdate?

Nic*_*ky 0 java sql jdbc

我想知道,如何在JAVA(JDBC)中关闭executeUpdate语句?

例如:

String sql = "UPDATE. .. . ..  Whatever...";
ResultSet rs = stmt.executeQuery(sql);
rs.close();
Run Code Online (Sandbox Code Playgroud)

但我不能这样更新.所以我用Google搜索并发现我需要使用executeUpdate但是如何在之后关闭语句?

String sql = "UPDATE. .. . ..  Whatever...";
int rs = stmt.executeUpdate(sql);
rs.close(); ??? <------
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 5

你不关闭executeUpdate,你关闭Statement:

rs.close();   // Closes the ResultSet
stmt.close(); // Closes the Statement
Run Code Online (Sandbox Code Playgroud)

通常最好使用try-with-resources语句执行此操作:

String sql = "UPDATE. .. . ..  Whatever...";
try (
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(sql);
) {
    // Process results
}
Run Code Online (Sandbox Code Playgroud)

try-with-resources将关闭StatementResultSet为您关闭.它是在Java 7中添加的(2011年).


旁注:你已经证明你正在使用Statement和打电话executeUpdate(String).只要SQL中没有外部源信息(用户输入或其他系统没有收到任何信息等),那就没问题了.但是,在更常见的情况下,您需要使用a PreparedStatement,调用setXyzset参数,然后调用executeUpdate()(zero-args版本).这种习惯可以防止SQL注入.有关这个有用网站的更多解释和示例:http://bobby-tables.com/.

  • @Nicky:不,当你完成`Statement`时你关闭`Statement`.请注意,在任何给定的时刻,您只能在`Statement`实例上打开一个`ResultSet`,所以在重复使用`Statement`获取另一个之前(或者不要),请确保您已完成第一个`ResultSet`重用`Statement`对象,我认为重用它没有任何真正的优势). (2认同)