Reputation: 63
i am trying to add my all data in the Jtable to the mysql database. but data added successfully. but Data Added twice into the database. I attached the screenshot below of database table how record added enter image description here
this is the code which i tried
try{
int rows=jTable1.getRowCount();
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con1=DriverManager.getConnection("jdbc:mysql://localhost/javasales","root","");
con1.setAutoCommit(false);
String queryco = "Insert into sales_product(product,price) values (?,?)";
PreparedStatement preparedStmt = (PreparedStatement) con1.prepareStatement(queryco,Statement.RETURN_GENERATED_KEYS);
for(int row = 0; row<rows; row++)
{
String product = (String)jTable1.getValueAt(row, 0);
String price = (String)jTable1.getValueAt(row, 1);
preparedStmt.setString(1, product);
preparedStmt.setString(2, price);
preparedStmt.executeUpdate();
ResultSet generatedKeyResult = preparedStmt.getGeneratedKeys();
preparedStmt.addBatch();
preparedStmt.executeBatch();
con1.commit();
}
JOptionPane.showMessageDialog(null, "Successfully Save");
}
catch(ClassNotFoundException | SQLException | HeadlessException e){
JOptionPane.showMessageDialog(this,e.getMessage());
}
Upvotes: 0
Views: 319
Reputation: 211
As in your code you are iterating each row one by one and on every iteration you are executing both :
preparedStmt.executeUpdate();
preparedStmt.executeBatch();
That's why same row has been inserted twice. You can go with below solutions to avoid multiple insertion.
Only use preparedStmt.executeUpdate();
within the loop and remove preparedStmt.executeBatch();
preparedStmt.executeUpdate();
ResultSet generatedKeyResult = preparedStmt.getGeneratedKeys();
// preparedStmt.addBatch();
// preparedStmt.executeBatch();
con1.commit();
}
Don't use preparedStmt.executeUpdate();
and move preparedStmt.executeBatch();
outside of loop.
//preparedStmt.executeUpdate();
//ResultSet generatedKeyResult = preparedStmt.getGeneratedKeys();
preparedStmt.addBatch();
}
preparedStmt.executeBatch();
con1.commit();
Upvotes: 1