Creating a prepared statement inside a loop

To clarify: I know what is right to create PreparedStatementoutside the loop. I asked this question only out of curiosity.


Suppose I create PreparedStatementinside a loop with always the same SQL query.

final String sql = "INSERT INTO ...";
while (condition) {
   ...
   PreparedStatement statement = connection.prepareStatement(sql);
   // Fill values of the prepared statement
   // Execute statement
   ...
}

Is it really useless, since the object is PreparedStatementalways recreated? Or does the underlying database recognize that it is always the same SQL query that creates PreparedStatementand reuses it?

+5
source share
5 answers

, . , Oracle: http://docs.oracle.com/cd/B10501_01/java.920/a96654/stmtcach.htm

, , , , JDBC. , MySQL : MySQL?

, , , , , .

+1

1. PreparedStatement , PreparedStatement .

2. sql statment, , .

3. , , Statement PreparedStatement, PreparedStatement , .

+8

.

1st Way

Record insert one after another

final String sql = "INSERT INTO tablename(columnname) Values(?)";

PreparedStatement statement = connection.prepareStatement(sql);

while (condition) {
statement.setString(1,value);
statement.executeUpdate();
}

(or)

Second way

Inserts an entire record as a nested insert

final String sql = "INSERT INTO tablename(columnname) Values(?)";

PreparedStatement statement = connection.prepareStatement(sql);

while (condition) {
statement.setString(1,value);
statement.addBatch();
}

statement.executeBatch();
+1
source

All Articles