PreparedStatement在一个循环中,如何使用

时间:2016-01-10 20:15:21

标签: java loops prepared-statement derby javadb

我正在尝试存储在private void Loaded(object sender, RoutedEventArg arg) { ... var text = textBox.Text; var binding = new Binding(); ... binding property here textBox.SetBinding(TextBox.TextProperty, binding); textBox.Text = text; var expression = BindingExpression.GetBindingExpression(textBox, TextBox.TextProperty); expression.UpdateSource(); } 表中创建的所有项目,我想知道我是否可以这样做:

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(); } ?和executeUpdate()?或者我需要做PreparedStatement吗?

2 个答案:

答案 0 :(得分:3)

在for循环中运行查询不是最佳做法。如果您使用批量更新,则最好如下:

go2 somefile.txt

答案 1 :(得分:2)

您需要为列表中的每个项目调用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(); } ,因此需要在循环内部。您只需要准备一次语句,以便它应该在循环之外。

所以:

{{1}}