java-将jTable中的数据插入数据库
作者:互联网
我试图将一些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插入数据?
解决方法:
将批处理的执行置于for循环之外,这是addBatch()的好处,因为它仅在一次调用executeBatch()时才访问数据库.
for(int row = 0; row<rows ; row++)
{
//......
stmt.addBatch();
}
stmt.executeBatch();
conn.commit();
标签:defaulttablemodel,swing,jtable,java,database 来源: https://codeday.me/bug/20191123/2064435.html