3

我正在尝试将一些 JTable 数据保存到数据库中:我的代码是这样的:

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){} }

}
 }

为什么这种方法根本没有效果?我在这里做错了吗?有没有其他系统可以直接从 jTable 插入数据?

4

1 回答 1

3

在for-loop之外执行批处理,这是它的好处,因为它只在被调用addBatch()时访问数据库一次。executeBatch()

for(int row = 0; row<rows ; row++)
  {
   //......
   stmt.addBatch();
 }
stmt.executeBatch();
conn.commit();
于 2013-07-16T21:50:25.207 回答