简体   繁体   English

循环中的PreparedStatement,如何使用

[英]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: 我正在尝试存储在ITEM表中创建的所有项目,我想知道是否可以做到这一点:

    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? 还是我需要在循环中包含executeUpdate() And the PreparedStatement ? 还有PreparedStatement Or do I need to do an executeBatch() ? 还是我需要执行executeBatch()

Running a query inside a for loop is not the best practice. 在for循环内运行查询不是最佳实践。 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();

You need to call executeUpdate for each item in the list, so it needs to be inside the loop. 您需要为列表中的每个项目调用executeUpdate ,因此它必须位于循环内。 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM