gpt4 book ai didi

java - 多次查询数据库的首选方式?

转载 作者:IT老高 更新时间:2023-10-29 00:11:40 25 4
gpt4 key购买 nike

在 Java 中使用 JDBC 时,普遍接受的查询数据库的方法是获取一个连接,从该连接创建一个语句,然后从该语句执行一个查询。

// load driver
Connection con = DriverManager.getConnection(..);
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery("SELECT..");
// ...

但是,我不确定如何处理对同一数据库的第二次查询。

  1. 能否在同一个 Statement 对象上安全地执行另一个查询,或者必须从 Connection 对象创建另一个语句才能执行另一个查询?

  2. 如果同一个 Statement 对象可以用于多个查询,那么 Statement 类的目的是什么(因为这样对于一个Connection.executeQuery() 方法是否存在)?

最佳答案

是的,您可以重用 Statement 对象,但是 executeQuery 返回的 ResultSet 对象会关闭已经打开的结果集。

参见 javadoc求解释

By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.

所以会发生以下情况:

// load driver
Connection con = DriverManager.getConnection(..);
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery("select ..");
// do something with result ... or not
ResultSet result2 = stmt.executeQuery("select ...");
// result is now closed, you cannot read from it anymore
// do something with result2
stmt.close(); // will close the resultset bound to it

例如,您可以在 jTDS 项目中找到 Statement 的开源实现。在Statement.executeQuery() method你可以看到对 initialize() 的调用那closes all the resultsets已经打开

protected void initialize() throws SQLException {
updateCount = -1;
resultQueue.clear();
genKeyResultSet = null;
tds.clearResponseQueue();
// FIXME Should old exceptions found now be thrown instead of lost?
messages.exceptions = null;
messages.clearWarnings();
closeAllResultSets();
}

关于java - 多次查询数据库的首选方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12963504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com