我想从eclipse向数据库中插入多行。我写了代码,但我觉得缺少了一些东西:
String SQL ="insert into INFO(ORDER_NO,ITEM_NAME,SERIAL_NO,P-CODE,QTY,RATE,TOTAL)values(?,?,?,?,?,?,?),(?,?,?,?,?,?,?)";
try {
PreparedStatement pst=con.prepareStatement(SQL);
pst.setString(1, order.getText());
pst.setString(2 ,item1.getSelectedItem().toString());
pst.setString(3,serial1.getSelectedItem().toString());
pst.setString(4,code1.getSelectedItem().toString());
pst.setString(5,qty.getText());
pst.setString(6,rat1.getSelectedItem().toString());
pst.setString(7,label_1_1.getText());
pst.setString(8, order.getText());
pst.setString(9 ,item2.getSelectedItem().toString());
pst.setString(10,serial2.getSelectedItem().toString());
pst.setString(11,code2.getSelectedItem().toString());
pst.setString(12,qty1.getText());
pst.setString(13,rat2.getSelectedItem().toString());
pst.setString(14,label_2.getText());
pst.execute();
JOptionPane.showMessageDialog(null,"Done");
pst.close();
}catch (SQLException e) {
e.printStackTrace();
}
答案 0 :(得分:2)
在JDBC中为多个插入使用批处理语句。 至少从Java 7开始,你应该使用try-with来自动关闭资源:
String SQL = "insert into INFO(ORDER_NO,ITEM_NAME,SERIAL_NO,P-CODE,QTY,RATE,TOTAL) values (?,?,?,?,?,?,?)";
try (PreparedStatement pst=con.prepareStatement(SQL)) {
pst.setString(1, order.getText());
pst.setString(2 ,item1.getSelectedItem().toString());
pst.setString(3,serial1.getSelectedItem().toString());
pst.setString(4,code1.getSelectedItem().toString());
pst.setString(5,qty.getText());
pst.setString(6,rat1.getSelectedItem().toString());
pst.setString(7,label_1_1.getText());
pst.addBatch();
pst.setString(1,order.getText());
pst.setString(2,item2.getSelectedItem().toString());
pst.setString(3,serial2.getSelectedItem().toString());
pst.setString(4,code2.getSelectedItem().toString());
pst.setString(5,qty1.getText());
pst.setString(6,rat2.getSelectedItem().toString());
pst.setString(7,label_2.getText());
pst.addBatch();
pst.executeBatch();
JOptionPane.showMessageDialog(null,"Done");
} catch (SQLException e) {
e.printStackTrace();
}
答案 1 :(得分:1)
您在一个查询中插入两行:
values (?,?,?,?,?,?,?),(?,?,?,?,?,?,?)
^^^
但是Oracle并不支持多行的values
。一个好的解决方案是每insert
个命令只插入一行。
另一种选择是Oracle的insert all
,例如:
INSERT ALL
INTO mytable (column1, column2, column_n) VALUES (expr1, expr2, expr_n)
INTO mytable (column1, column2, column_n) VALUES (expr1, expr2, expr_n)
INTO mytable (column1, column2, column_n) VALUES (expr1, expr2, expr_n)
SELECT * FROM dual;