Insert data from jTable into Database

Pranjal Choladhara picture Pranjal Choladhara · Jul 16, 2013 · Viewed 7.9k times · Source

I am trying to save some JTable Data into Database: My code is like this:

public void save(){
String invSL = new Mixed_Calculation().invoice_Sl();
jTextField6.setText(invSL);

int rows = jTable1.getRowCount();


for(int row = 0; row<rows ; row++){

String code = (String) jTable1.getValueAt(row, 1);
String name = (String) jTable1.getValueAt(row, 2);
String unit = (String) jTable1.getValueAt(row, 3); 

    String units[] = unit.split(" ");
    int q = Integer.parseInt(units[0]);
    String u = units[1];

  String rate = (String) jTable1.getValueAt(row, 4);
  String total = (String) jTable1.getValueAt(row, 5);
  String d_rat = (String) jTable1.getValueAt(row, 6);
  String discount = (String) jTable1.getValueAt(row, 7);
  String net = (String) jTable1.getValueAt(row, 8); 


 try{
 conn = new connection().db();  
 conn.setAutoCommit(false);  


  String query = "INSERT INTO INVOICE(INVOICE_NO, CODE, DESCRIPTION, BONUSABLE,"
        + " TAXABLE, CATEGORY, QNTY, UNIT, RATE, TOTAL , DISC_PERCENTAGE, DISCOUNT, NET_AMOUNT ) "
        + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " ;


 stmt = conn.prepareStatement(query);
 stmt.setString(1, jTextField6.getText()); //Invoice No
 stmt.setString(2, code); //Code
 stmt.setString(3, name); //Description
 stmt.setString(4, ""); //Bonusable
 stmt.setString(5, ""); //Taxable
 stmt.setString(6, ""); //Category
 stmt.setInt(7, q); //Qnty
 stmt.setString(8, u); //Unit
 stmt.setDouble(9, Double.parseDouble(rate)); //Rate
 stmt.setDouble(10, Double.parseDouble(total)); //Total
 stmt.setDouble(11, Double.parseDouble(d_rat)); //Disc_%
 stmt.setDouble(12, Double.parseDouble(discount)); //Discount
 stmt.setDouble(13, Double.parseDouble(net)); //net_Amount

 stmt.addBatch(); stmt.executeBatch();
 conn.commit();

 }

 catch(SQLException ex){
  JOptionPane.showMessageDialog(null, "Cannot save. "+ ex);
    } 
   finally{try{stmt.close(); conn.close(); conn.setAutoCommit(true);}        catch(SQLException ex){} }

}
 }

Why this method has no effect at all ? Am I doing something wrong here ? Is there any other system, that I can insert data directly from jTable ?

Answer

Azad picture Azad · Jul 16, 2013

Take the execution of the batch outside the for-loop, that's the benefit of addBatch() as it hits the database only one time when executeBatch() is called.

for(int row = 0; row<rows ; row++)
  {
   //......
   stmt.addBatch();
 }
stmt.executeBatch();
conn.commit();