Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are the parameter values automatically cleared after executing a batch of SQL commands with a Java PreparedStatemen?

I have the following code snippet:

PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < 100000; i++) {
    preparedStatement.setObject(1, someValue);
    preparedStatement.addBatch();
    if ((i + 1) % 100 == 0) {
        preparedStatement.executeBatch();
    }
}

so I want to execute one command around 100 000 times with different values. My question is: are the parameters from the PreparedStatement cleared after each call to executeBatch() or do I have to explicitly call preparedStatement.clearParameters() after calling executeBatch() in order to make sure that there will be executed only the last 100 commands?

like image 798
Clara Avatar asked Feb 08 '12 11:02

Clara


People also ask

Which methods on the PreparedStatement can be used to bind the parameters?

The setXXX() methods bind values to the parameters, where XXX represents the Java data type of the value you wish to bind to the input parameter.

What does PreparedStatement do in Java?

Overview of Prepared Statements If you want to execute a Statement object many times, it usually reduces execution time to use a PreparedStatement object instead. The main feature of a PreparedStatement object is that, unlike a Statement object, it is given a SQL statement when it is created.

Which Statement of JDBC should be used to set the values for the parameters for SQL dynamically?

Set parameters dynamically to prepared Statement in JDBC.

Are Prepared statements actually compiled?

PreparedStatement uses SQL statements to send the data to DBMS right away after being compiled. It just not contain SQL statement, but a SQL statement that has been precompiled.


2 Answers

YES. According to section 15.1.2 of JDBC 3.0 and section 14.1.2 of JDBC 4.1:

Calling the method executeBatch closes the calling Statement object’s current result set if one is open. The statement’s batch is reset to empty once executeBatch returns.

It's unfortunate that such an important detail ended up almost as a fine print.

In addition to the example already mentioned, the jtds driver also does a clearBatch() in the finally block of executeBatch().

like image 140
Bogdan Calmac Avatar answered Oct 20 '22 00:10

Bogdan Calmac


As I can see here: http://javasourcecode.org/html/open-source/jdk/jdk-6u23/sun/jdbc/odbc/JdbcOdbcStatement.java.html

executeBatch() calls clearBatch() in the end.

But there is no guarantee for that will be exactly the same in other implementations.

like image 27
dhblah Avatar answered Oct 20 '22 00:10

dhblah