使用单个 JDBC Statement 对象执行多个查询

新手上路,请多包涵

在 JDBC 中,我可以使用单个 Statement 对象来多次调用 executeQuery("") 吗?安全吗?或者我应该在每次查询后关闭语句对象,并创建新对象以执行另一个查询。

例如:

 Connection con;
Statement s;
ResultSet rs;
ResultSet rs2;
try
{
    con = getConnection();
    // Initially I was creating the Statement object in an
    // incorrect way. It was just intended to be a pseudocode.
    // But too many answerers misinterpretted it wrongly. Sorry
    // for that. I corrected the question now. Following is the
    // wrong way, commented out now.
    // s = con.prepareStatement();

    // Following is the way which is correct and fits for my question.
    s = con.createStatement();

    try
    {
        rs = s.executeQuery(".......................");

        // process the result set rs
    }
    finally
    {
        close(rs);
    }

    // I know what to do to rs here
    // But I am asking, should I close the Statement s here? Or can I use it again for the next query?

    try
    {
        rs2 = s.executeQuery(".......................");

        // process the result set rs2
    }
    finally
    {
        close(rs2);
    }
}
finally
{
    close(s);
    close(con);
}

原文由 Syed Aqeel Ashiq 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.9k
2 个回答

我不确定你为什么要问。 The API design and documentation show it is perfectly fine (and even intended) to reuse a Statement object for multiple execute , executeUpdate and executeQuery 电话。如果不允许,则将在 Java 文档中明确记录(并且 API 可能会有所不同)。

此外 Statement 的 apidoc 说:

Statement 接口中的所有执行方法都会隐式关闭语句的 [ 原文如此] 当前 ResultSet 对象(如果存在打开的对象)。

这表明您可以多次使用它。

TL;DR:是的,您可以在单个 Statement 对象上多次调用 execute ,只要您意识到之前打开的任何 ResultSet 将被关闭。

您的示例错误地使用 PreparedStatement ,并且您不能(或:不应)调用任何 接受 Stringexecute... PreparedStatement

SQLException - 如果 […] 在 PreparedStatementCallableStatement 上调用该方法

但是要回答 PreparedStatement 以及: PreparedStatement 的全部目的是预编译带有参数占位符的语句并将其重用于具有不同参数值的多次执行。

原文由 Mark Rotteveel 发布,翻译遵循 CC BY-SA 3.0 许可协议

首先,我对您的代码感到困惑

s = con.prepareStatement();

效果好吗?我在JAVA API中找不到这样的函数,至少需要一个参数。也许你想调用这个函数

s = con.createStatement();

我刚刚运行我的代码以使用一个 Statement 实例访问 DB2 两次,而没有在两次操作之间关闭它。它工作得很好。我想你也可以自己尝试一下。

     String sql = "";
    String sql2 = "";
    String driver = "com.ibm.db2.jcc.DB2Driver";
    String url = "jdbc:db2://ip:port/DBNAME";
    String user = "user";
    String password = "password";
    Class.forName(driver).newInstance();
    Connection conn = DriverManager.getConnection(url, user, password);
    Statement statement = conn.createStatement();
    ResultSet resultSet = statement.executeQuery(sql);
    int count = 0;
    while (resultSet.next()) {
        count++;
    }
    System.out.println("Result row count of query number one is: " + count);
    count = 0;
    resultSet = statement.executeQuery(sql2);
    while (resultSet.next()) {
        count++;
    }
    System.out.println("Result row count of query number two is: " + count);

原文由 mojiayi 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题