2

Is recommended to create just one Statement object and execute multiple executeUpdate() on it?

// Vantages/drawbacks of this solution?
conn.setAutocommit(false);

Statement stmt = conn.createStatement();
stmt.executeUpdate('[ANY_INSERT_SQL]');
stmt.executeUpdate('[ANY_INSERT_SQL]');
stmt.executeUpdate('[ANY_INSERT_SQL]');

conn.commit();

Or is better one Statement object for each executeUpdate:

// Vantages/drawbacks of this solution?
conn.setAutocommit(false);

Statement stmt1 = conn.createStatement();
stmt1.executeUpdate('[ANY_INSERT_SQL]');
Statement stmt2 = conn.createStatement();
stmt2.executeUpdate('[ANY_INSERT_SQL]');
Statement stmt3 = conn.createStatement();
stmt3.executeUpdate('[ANY_INSERT_SQL]');

conn.commit();

Thanks in advance.

PS: I know PreparedStatement class and I use it often, but my doubt is about Statement usage.

2 Answers 2

4

It doesn't matter, just make sure you close all statement objects.

Sign up to request clarification or add additional context in comments.

Comments

1

Based on the javadoc, A statement can have only one associated ResultSet object.

The object used for executing a static SQL statement and returning the results it produces.

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.

http://download.oracle.com/javase/1.4.2/docs/api/java/sql/Statement.html

If you need to process multiple results sets at the same time, perhaps, more statements make sense.

Probably more often than not, you only need to use one.

Performance-wise, probably better as it keeps fewer resources active.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.