java-无法将多个数据插入数据库

时间:2019-01-13 03:02:17

标签: java mysql database netbeans

我有一些代码可以保存到两个数据库中,但另一个不能保存到数据库中。无法保存的是从jtable中插入3个值的多行数据,但是我在数据库中有5列,因为我需要用其他值临时将其填充为空。这是代码:

private void btnSimpanActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    try{
        String sql="INSERT INTO pinjam VALUES('"+noPeminjaman.getText()+
                "','"+noMember.getText()+"','"+tglPinjam.getText()+"',1)";
        java.sql.Connection conn = (Connection)Config.configDB();
        java.sql.PreparedStatement pst = conn.prepareStatement(sql);
        pst.execute();

        //Simpan ke pinjam_detil
        int rows = tabelPinjam.getRowCount();
        for(int row = 0; row<rows; row++){
            String idBuku = (String)tabelPinjam.getValueAt(row, 0);
            String tglTempo = (String)tabelPinjam.getValueAt(row, 2);
            try{
                String query = "INSERT INTO pinjam_detil (idpinjam,idbuku,tgl_tempo) "
                        + "VALUES(?,?,?)";

                java.sql.PreparedStatement stmt = conn.prepareStatement(query);
                stmt.setString(1, noPeminjaman.getText());
                stmt.setString(2, idBuku);
                stmt.setString(3, tglTempo);



                stmt.addBatch();
                stmt.executeBatch();
            }catch(Exception ex){}
        }
        JOptionPane.showMessageDialog(null, "Successfully Save");
    }catch(Exception e){}
    resetForm();
}

1 个答案:

答案 0 :(得分:1)

不要捕获异常,什么也不做。最好向该方法添加一个throws子句,如下所示:

private void doThingie() throws SQLException {}

如果这不是一个选项,则应在您的catch块中:

new RuntimeException(e);

因为现在发生了一些错误,您无法分辨,因为您一直在默默忽略它。

此外,它只是stmt.execute();,而不是addBatch + executeBatch

相关问题