简体   繁体   English

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

[英]Execute multiple queries using a single JDBC Statement object

In JDBC, can I use single Statement object to call executeQuery("") multiple times?在 JDBC 中,我可以使用单个Statement对象多次调用executeQuery("")吗? Is it safe?安全吗? Or should I close the statement object after each query, and create new object for executing another query.或者我应该在每次查询后关闭语句对象,并创建新对象来执行另一个查询。

EG:例如:

Connection con;
Statement s;
ResultSet rs;
ResultSet rs2;
try
{
    con = getConnection();
    s = con.prepareStatement();

    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);
}

Yes you can re-use a Statement (specifically a PreparedStatement ) and should do so in general with JDBC.是的,您可以重复使用Statement (特别是PreparedStatement ),并且通常应该使用 JDBC 这样做。 It would be inefficient & bad style if you didn't re-use your statement and immediately created another identical Statement object.如果您不重用您的语句并立即创建另一个相同的Statement对象,那将是低效和糟糕的风格。 As far as closing it, it would be appropriate to close it in a finally block, just as you are in this snippet.至于关闭它,最好在 finally 块中关闭它,就像您在此代码段中一样。

For an example of what you're asking check out this link: jOOq Docs有关您要问的内容的示例,请查看此链接: jOOq Docs

I am not sure why you are asking.我不确定你为什么要问。 The API design and documentation show it is perfectly fine (and even intended) to reuse a Statement object for multiple execute , executeUpdate and executeQuery calls. API 设计和文档表明,将Statement对象重用于多个executeexecuteUpdateexecuteQuery调用是非常好的(甚至有意)。 If it wouldn't be allowed that would be explicitly documented in the Java doc (and likely the API would be different).如果不允许,则会在 Java 文档中明确记录(并且 API 可能会有所不同)。

Furthermore the apidoc of Statement says:此外, Statement的 apidoc 说:

All execution methods in the Statement interface implicitly close a statment's [ sic ] current ResultSet object if an open one exists.如果存在打开的对象,则Statement接口中的所有执行方法都会隐式关闭语句的 [原文如此] 当前ResultSet对象。

This is an indication that you can use it multiple times.这表明您可以多次使用它。

TL;DR: Yes, you can call execute on single Statement object multiple times, as long as you realize that any previously opened ResultSet will be closed. TL;DR:是的,您可以多次对单个Statement对象调用execute ,只要您意识到任何先前打开的ResultSet将被关闭。

Your example incorrectly uses PreparedStatement , and you cannot (or: should not) be able to call any of the execute... methods accepting a String on a PreparedStatement :您的示例错误地使用PreparedStatement ,并且您不能(或:不应该)能够调用任何接受PreparedStatement上的Stringexecute...方法

SQLException - if [...] the method is called on a PreparedStatement or CallableStatement SQLException - 如果 [...] 在PreparedStatementCallableStatement该方法

But to answer for PreparedStatement as well: the whole purpose of a PreparedStatement is to precompile a statement with parameter placeholders and reuse it for multiple executions with different parameter values.但要答案PreparedStatement还有:一个的整个目的PreparedStatement是预编译与参数占位符的声明,并重新使用它与不同的参数值多次执行。

I can't find anything in the API docs that would state, that you shouldn't call executeQuery() on a given PreparedStatement instance more than once.我在API 文档中找不到任何可以说明您不应在给定PreparedStatement实例上多次调用executeQuery()内容。

However your code does not close the PreparedStatement - a call to executeQuery() would throw a SQLException in that case - but the ResultSet that is returned by executeQuery() .但是你的代码不会关闭PreparedStatement -到呼叫executeQuery()将抛出SQLException在这种情况下-但ResultSet是由返回executeQuery() A ResultSet is automatically closed , when you reexecute a PreparedStatement .当您重新执行PreparedStatement时,ResultSet 会自动关闭 Depending on your circumstances you should close it, when you don't need it anymore.根据您的情况,您应该在不再需要它时关闭它。 I would close it, because i think it's bad style not to do so.我会关闭它,因为我认为不这样做是不好的风格。

UPDATE Upps, I missed your comment between the two try blocks.更新Upps,我错过了您在两个 try 块之间的评论。 If you close your PreparedStatement at this point, you shouldn't be able to call executeQuery() again without getting a SQLException.如果此时关闭 PreparedStatement,则不应该在没有得到 SQLException 的情况下再次调用 executeQuery()。

A Prepared Statement tells the database to remember your query and to be prepared to accept parameterized variables to execute in that query. Prepared Statement告诉数据库记住您的查询并准备好接受参数化变量以在该查询中执行。 It's a lot like a stored procedure.它很像一个存储过程。

Prepared Statement accomplishes two main things: Prepared Statement主要完成两件事:

  1. It automatically escapes your query variables to help guard against SQL Injection.它会自动转义您的查询变量以帮助防止 SQL 注入。

  2. It tells the database to remember the query and be ready to take variables.它告诉数据库记住查询并准备好接受变量。

Number 2 is important because it means the database only has to interpret your query once, and then it has the procedure ready to go.数字 2 很重要,因为它意味着数据库只需要解释一次您的查询,然后它就可以准备执行该过程。 So it improves performance.所以它提高了性能。

You should not close a prepared statement and/or the database connection in between execute calls.您不应在执行调用之间关闭准备好的语句和/或数据库连接。 Doing so is incredibly in-efficient and it will cause more overhead than using a plain old Statement since you instruct the database each time to create a procedure and remember it.这样做效率低得令人难以置信,而且会比使用普通的旧Statement导致更多的开销,因为您每次都指示数据库创建一个过程并记住它。 Even if the database is configured for "hot spots" and remembers your query anyways even if you close the PreparedStatement , you still incur network overhead as well as small processing time.即使数据库被配置为“热点”并且即使关闭PreparedStatement仍然记住您的查询,您仍然会产生网络开销以及小的处理时间。

In short, keep the Connection and PreparedStatement open until you are done with them.简而言之,保持ConnectionPreparedStatement打开,直到您完成它们。

Edit: To comment on not returning a ResultSet from the execution, this is fine.编辑:要评论不从执行中返回ResultSet ,这很好。 executeQuery will return the ResultSet for whatever query just executed. executeQuery将为刚刚执行的任何查询返回ResultSet

Firstly I am confused about your code首先我对你的代码感到困惑

s = con.prepareStatement();

Is it work well?I can't find such function in JAVA API,at least one parameter is needed.Maybe you want to invoke this function效果好吗

s = con.createStatement();

I just ran my code to access DB2 for twice with one single Statement instance without close it between two operation.It's work well.I think you can try it yourself too.我只是用一个 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在JDBC中的单个语句对象上使用batchExecute和execute方法 - Using batchExecute and execute methods on a single statement object in JDBC 使用相同的语句对象在多个线程中执行多个查询? - using same statement object to execute multiple queries in multiple threads? 使用java使用语句类的单个execute()方法执行多个hive查询 - Execute multiple hive queries using single execute() method of statement class using java 如何在单个 JDBC 连接中执行多个 JPA 查询 - How to Execute multiple JPA queries in a single JDBC Connection 使用Java程序中的JDBC执行多个sql SELECT查询 - Execute multiple sql SELECT queries using JDBC from a Java Program 使用jdbc对数据库进行多次查询 - Multiple queries on database using jdbc 使用JButton通过JDBC执行SQL查询 - Using JButtons to execute SQL queries with JDBC 使用Java在单个语句中运行多个Hive查询时出错 - Error in Running multiple Hive Queries in single statement using Java 使用 JDBC Statement 或 PreparedStatement 执行一组查询 - Executing set of queries using JDBC Statement or PreparedStatement 使用Spring JDBC模板在单个事务中执行多个查询(插入和更新) - Executing Multiple queries (Insert and Update) in single transaction using Spring JDBC template
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM