如果我使用 JDBC 创建一条语句并执行查询,我是否需要关闭该语句并在再次执行之前创建一个新语句?Eclipse 不会抱怨第二种情况。
try {
connection = dataSource.getConnection();
try {
statement = connection.createStatement();
statement.execute("set search_path to '...'");
} finally {
Utils.tryClose(statement);
}
try {
statement = connection.createStatement();
statement.execute("SET statement_timeout TO " + (QUERY_TIMEOUT_SECONDS * 1000));
} finally {
Utils.tryClose(statement);
}
try {
statement = connection.createStatement();
statement.execute(query);
} finally {
Utils.tryClose(statement);
}
} finally {
Utils.tryClose(connection);
}
Run Code Online (Sandbox Code Playgroud)
相对于:
try {
connection = dataSource.getConnection();
statement = connection.createStatement();
statement.execute("set search_path to '...'");
statement.execute("SET statement_timeout TO " + (QUERY_TIMEOUT_SECONDS * 1000));
statement.execute(query);
} finally {
Utils.tryClose(statement);
Utils.tryClose(connection);
}
Run Code Online (Sandbox Code Playgroud)
这并不要求您可以使用相同的语句多次查询数据库,唯一要记住的是,语句执行返回的每个结果集将在创建新的状态网后关闭。引用自java文档:-
默认情况下,每个 Statement 对象只能同时打开一个 ResultSet 对象。因此,如果一个 ResultSet 对象的读取与另一个 ResultSet 对象的读取交错,则每个 ResultSet 对象都必须由不同的 Statement 对象生成。如果存在打开的 ResultSet 对象,Statement 接口中的所有执行方法都会隐式关闭该语句的当前 ResultSet 对象。
因此你可以这样做:-
try {
connection = dataSource.getConnection();
statement = connection.createStatement();
ResultSet rs1=statement.execute("....");
//parse rs1
//close rs1
ResultSet rs2= statement.execute(....);
//parse rs1
//close rs1
} finally {
Utils.tryClose(statement);
Utils.tryClose(connection);
}
Run Code Online (Sandbox Code Playgroud)
我不知道为什么 Eclipse 会抱怨 的情况PreparedStatements
,整个目的PreparedStatements
是定义一个查询结构并通过仅更改参数来多次执行查询。例如,当您想要解析大型文本文件并将其插入数据库时。引用自javadoc
如果要多次执行Statement对象,通常可以使用PreparedStatement对象来减少执行时间。