1

I was wondering if it is a good practice to execute a PreparedStatement multiple times or we should reinitialize it each time.

For example:

while(i<100){
    PreparedStatement ptsmt = con.preparedStatement("INSERT into counts (counter) values (?)"); 
    ptsmt.setInt(1,i);
    ptsmt.executeUpdate();
}

Is worse or better than ?

PreparedStatement ptsmt = con.preparedStatement("INSERT into counts (counter) values (?)"); 
while(i<100){
    ptsmt.setInt(1,i);
    ptsmt.executeUpdate();
}
ponomandr
  • 1,523
  • 13
  • 21
Eastern Monk
  • 6,395
  • 8
  • 46
  • 61

2 Answers2

4

The second code is recomended. The PreparedStatement is intended to be reused. Read what the documentation says:

A SQL statement is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.

Remember to always call clearParameters() before reusing it:

PreparedStatement pstmt = conn.preparedStatement(
        "INSERT INTO counts (counter) VALUES (?)"); 
while (i < 100) {
    pstmt.clearParameters();
    pstmt.setInt(1, ++i);
    pstmt.executeUpdate();
}
ericbn
  • 10,163
  • 3
  • 47
  • 55
1

Prefer the second one. The whole point is to create it once and reuse it.

duffymo
  • 305,152
  • 44
  • 369
  • 561