Kaine
Kaine

Reputation: 41

java - cant insert multiple data to database

i have some code that will save into two database but the other one can't saving into database. the one that can't to save is inserting multiple row data from jtable with 3 values but i have 5 columns in database because i need to fill it temporary with the other values are null. this is the code :

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

Upvotes: 2

Views: 156

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 102903

Don't catch an exception and do nothing. Preferably, add a throws clause to the method, like so:

private void doThingie() throws SQLException {}

and if that's not an option, this should be in your catch block:

new RuntimeException(e);

because right now some error is happening and you can't tell because you're silently ignoring it.

Also, it's just stmt.execute();, not addBatch+executeBatch

Upvotes: 1

Related Questions