Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PreparedStatement in a loop, how to use

I'm trying to store all the items that were created in the ITEM table and I wonder if I can do that:

    PreparedStatement stm = null;
    //String sql = "INSERT INTO ITEM (ID, TYPE, TITEL, UITGELEEND) VALUES ('%s', '%s', '%s', %b)";

    try {
        stm = db.prepareStatement("INSERT INTO ITEM (ID, TYPE, TITEL, UITGELEEND) VALUES (?, ?, ?, ?)");

        for (int n = 0; n < ItemLijst.getItems().size(); n++) {
            Item huidigItem = ItemLijst.getItemObvIdx(n);

            stm.setString(1, huidigItem.getID().toString());
            stm.setString(2, huidigItem.getType().toString());
            stm.setString(3, huidigItem.getTitel());
            stm.setString(4, String.valueOf(huidigItem.isUitgeleend()));
        }
        stm.executeUpdate();
        stm.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }

Or do I need to include the executeUpdate() in the loop? And the PreparedStatement? Or do I need to do an executeBatch()?


2 Answers

Running a query inside a for loop is not the best practice. It is better if you use batch update as the following:

stm = db.prepareStatement("INSERT INTO ITEM (ID, TYPE, TITEL, UITGELEEND) VALUES (?, ?, ?, ?)");
db.setAutoCommit(false);  
for (int n = 0; n < ItemLijst.getItems().size(); n++) {
     Item huidigItem = ItemLijst.getItemObvIdx(n);
     stm.setString(1, huidigItem.getID().toString());
     stm.setString(2, huidigItem.getType().toString());
     stm.setString(3, huidigItem.getTitel());
     stm.setString(4,String.valueOf(huidigItem.isUitgeleend()));
     stm.addBatch();
     }
stm.executeBatch();
db.commit();
like image 72
Pritam Banerjee Avatar answered Oct 25 '25 23:10

Pritam Banerjee


You need to call executeUpdate for each item in the list, so it needs to be inside the loop. You only need to prepare the statement once so that should be outside of the loop.

So:

try {
    stm = db.prepareStatement("INSERT INTO ITEM (ID, TYPE, TITEL, UITGELEEND) VALUES (?, ?, ?, ?)");

    for (int n = 0; n < ItemLijst.getItems().size(); n++) {
        Item huidigItem = ItemLijst.getItemObvIdx(n);

        stm.setString(1, huidigItem.getID().toString());
        stm.setString(2, huidigItem.getType().toString());
        stm.setString(3, huidigItem.getTitel());
        stm.setString(4, String.valueOf(huidigItem.isUitgeleend()));

        stm.executeUpdate();
    }
    stm.close();
} catch (SQLException e) {
    e.printStackTrace();
}
like image 33
greg-449 Avatar answered Oct 25 '25 22:10

greg-449



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!