I do this:

PreparedStatement ps = conn.prepareStatement( "INSERT INTO mydbcall1.Call0 (date,direction,operator,abonentTel,duration,coast1,coast2,corpPhone)" + " VALUES(?, ?, ?, ?, ?, ?, ?, ?)"); try { ps.setDate(1, new java.sql.Date(call.date.getTime()) ); ps.setString(2, call.direction); ps.setString(3, call.operator); ps.setString(4, call.abonentTel); ps.setInt(5, call.duration); ps.setDouble(6, call.coast1); ps.setDouble(7, call.coast2); ps.setString(8, call.corpPhone); ps.executeUpdate(); // for INSERT, UPDATE & DELETE } finally { ps.close(); } 

The method for 3000 objects works more than 1.5 minutes.

    1 answer 1

    1. Do not create a PreparedStatement each time. The advantage of PreparedStatement over a regular Statement is that it can be sent in advance to the database server for compilation and reused.

    2. Send batch inserts. You may have to find the optimal package size.

    3. Use explicit transaction management. By default, the transaction is completed for each database request ( autoCommit = true ).

    Here is an example using these three guidelines (using try-with-resources ):

     private static final String INSERT_STATEMENT = "INSERT INTO mydbcall1.Call0(date,direction,operator,abonentTel,duration,coast1,coast2,corpPhone) VALUES(?, ?, ?, ?, ?, ?, ?, ?)"; // .... try ( Connection connection = database.getConnection(); PreparedStatement ps = connection.prepareStatement(INSERT_STATEMENT); ) { int i = 0; connection.setAutoCommit(false) for (Call call : calls) { ps.setDate(1, new java.sql.Date(call.date.getTime()) ); ps.setString(2, call.direction); ps.setString(3, call.operator); ps.setString(4, call.abonentTel); ps.setInt(5, call.duration); ps.setDouble(6, call.coast1); ps.setDouble(7, call.coast2); ps.setString(8, call.corpPhone); // ... ps.addBatch(); i++; if (i % 1000 == 0 || i == calls.size()) { ps.executeBatch(); // ограничиваем размер одного пакета тысячей вставок } } connection.commit(); } catch(SQLException e) { connection.rollback(); } 
    • Nofate, thank you very much. With Batch, everything should be much faster. Very helpful !! - KirillN
    • statement.executeBatch (); - I can not understand. Where did this article come from? is he announced? - KirillN
    • one
      @KirillN, corrected, there ps, of course - Nofate
    • I'm already using ps. THX! - KirillN