循环中的PreparedStatement,如何使用 [英] PreparedStatement in a loop, how to use

查看:168
本文介绍了循环中的PreparedStatement,如何使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图将所有在 ITEM 表中创建的项目存储起来,我想知道是否可以做到这一点:

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();
    }

还是我需要在循环中包含 executeUpdate()?还有 PreparedStatement ?还是我需要做一个 executeBatch()?

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

推荐答案

在for循环内运行查询不是最佳实践.最好使用以下批处理更新:

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();

这篇关于循环中的PreparedStatement,如何使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆