将数据从jTable插入数据库

时间:2013-07-16 21:22:33

标签: java database swing jtable defaulttablemodel

我正在尝试将一些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插入数据吗?

1 个答案:

答案 0 :(得分:3)

for-loop 之外执行批处理,这是addBatch()的好处,因为当executeBatch()for(int row = 0; row<rows ; row++) { //...... stmt.addBatch(); } stmt.executeBatch(); conn.commit(); 时它只会到达数据库一次调用。

{{1}}