如何将表的多行数据插入到DB中?

时间:2017-01-19 09:52:49

标签: java database rows

这是我的代码,我想将两行数据存入我的数据库,但是当我只将最后一行或第二行数据设置到我的数据库表中时:

try{

int rows=tblCO2.getRowCount();

 for(int row = 0; row<rows; row++)
  {
    System.out.println(row);
    String itemcode = (String)tblCO2.getValueAt(row, 0);
    String lotno = (String)tblCO2.getValueAt(row, 1);
    String stackno = (String)tblCO2.getValueAt(row, 2);
    String grade = (String)tblCO2.getValueAt(row, 3);
    String ctns = (String)tblCO2.getValueAt(row, 4);

    try
    {
        Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
        conn = DriverManager.getConnection("jdbc:derby://localhost:1527/demo","user","pw");
        conn.setAutoCommit(false);
        String queryco = "Insert into alicreative.pur(itemcode,lotno,stackno,grade,ctns) values (?,?,?,?,?)";
        pst = conn.prepareStatement(queryco);
        pst.setString(1, itemcode);
        pst.setString(2, lotno);
        pst.setString(3, stackno);
        pst.setString(4, grade);
        pst.setString(5, ctns);
        pst.addBatch();
    }
    catch(ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e)
    {
        JOptionPane.showMessageDialog(this,e.getMessage());
    }


}
pst.executeBatch();
conn.commit();
}
catch(  HeadlessException | SQLException e){
    JOptionPane.showMessageDialog(this,e.getMessage());
}

请告诉我解决方案,在一个操作中保存两行数据。

2 个答案:

答案 0 :(得分:0)

您正在为每一行创建一个新的Connection对象。为什么?

(因此,您还拥有与行数一样多的不同PreparedStatement对象。在循环结束后实际执行多少和哪一个?)

答案 1 :(得分:0)

在循环之前初始化PreparedStatement(并创建连接),因为实际上,您在每次迭代时创建一个新的,并用一个批处理填充它。

最后,您最终只执行最后一个PreparedStatement(仅包含最后一行的批次)。

try{

int rows=tblCO2.getRowCount();

Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/demo","user","pw");
conn.setAutoCommit(false);
String queryco = "Insert into alicreative.pur(itemcode,lotno,stackno,grade,ctns) values (?,?,?,?,?)";
PreparedStatement pst = conn.prepareStatement(queryco);

for(int row = 0; row<rows; row++)
{
    System.out.println(row);
    String itemcode = (String)tblCO2.getValueAt(row, 0);
    String lotno = (String)tblCO2.getValueAt(row, 1);
    String stackno = (String)tblCO2.getValueAt(row, 2);
    String grade = (String)tblCO2.getValueAt(row, 3);
    String ctns = (String)tblCO2.getValueAt(row, 4);

    try
    {

        pst.setString(1, itemcode);
        pst.setString(2, lotno);
        pst.setString(3, stackno);
        pst.setString(4, grade);
        pst.setString(5, ctns);
        pst.addBatch();
    }
    catch(ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e)
    {
        JOptionPane.showMessageDialog(this,e.getMessage());
    }


}
pst.executeBatch();
conn.commit();
}
catch(  HeadlessException | SQLException e){
    JOptionPane.showMessageDialog(this,e.getMessage());
}