BackSlash
BackSlash

Reputation: 22233

Listening to batch queries with PreparedStatement in Java

Let's say we have this snippet:

dbConnection.setAutoCommit(false);//commit trasaction manually

String insertTableSQL = "INSERT INTO DBUSER"
            + "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
            + "(?,?,?,?)";              
PreparedStatement = dbConnection.prepareStatement(insertTableSQL);

for(int i=0;i<5000;i++){
    preparedStatement.setInt(1, 101);
    preparedStatement.setString(2, "im_a_new_user");
    preparedStatement.setString(3, "admin");
    preparedStatement.setTimestamp(4, "00:00:00.000");
    preparedStatement.addBatch();
}

preparedStatement.executeBatch();

dbConnection.commit();

It basically adds 5000 batch inserts to the PreparedStatement and executes them.

Now, i have a GUI with a JProgressBar, and I would like to listen to the PreparedStatement after the executeBatch() call, in order to know how many queries have been executed and update the progress bar. I already have the code to update the progressbar but i don't know how to listen to PreparedStatement, is it possible to do that?

Upvotes: 0

Views: 1055

Answers (1)

ogzd
ogzd

Reputation: 5692

You can divide whole data into bulks and treat each of them individually and update the progress bar afterwards.

private int BULKSIZE = 100; // define your own bulk size

for(int j = 0; j < 5000; j += BULKSIZE)
{
    for(int i = 0; i < BULKSIZE; ++i) 
    {
         preparedStatement.setInt(1, 101);
         preparedStatement.setString(2, "im_a_new_user");
         preparedStatement.setString(3, "admin");
         preparedStatement.setTimestamp(4, "00:00:00.000");
         preparedStatement.addBatch();
    }
    preparedStatement.executeBatch();
    updateProgressBar();
}

Upvotes: 3

Related Questions