我試圖從我的jFrame表單保存一些字段,但是當我點擊保存按鈕時,我得到空指針異常。以前我得到的錯誤,文本字段不能爲空,所以我取消選中不爲空,但它沒有工作,我決定不包括Voucher_no在MySQL插入語句,因爲它是一個自動增量和其文本字段不可編輯 我的代碼有問題嗎? 正在使用Mysql Workbench。未保存到db的jFrame字段
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/canning?zeroDateTimeBehavior=convertToNull", "root", "");
con.setAutoCommit(false);
try {
// String kb = jTextField3.getText(); //voucher_no
String kc = (String) jComboBox3.getSelectedItem(); //factory
String kg = jTextField10.getText(); //fuel
Double ks = Double.valueOf(kg);
String ke = jTextField11.getText(); //electricity
Double kt = Double.valueOf(ke);
String kf = jTextField12.getText(); //manpower
Double ku = Double.valueOf(kf);
String kj = (String) jComboBox4.getSelectedItem(); //can_name
String kk = (String) jComboBox5.getSelectedItem(); //label name
String kq = jTextField23.getText();//no_of_cans
Double kv = Double.valueOf(kq);
String kr = jTextField24.getText();//no_of_labels
Double kw = Double.valueOf(kr);
String query1= "insert into production (date,factory,fuel,electricity,manpower,can_name,label_name,no_of_cans,no_of_labels)"
+ "values (?,?,?,?,?,?,?,?,?)";
try (PreparedStatement pst = con.prepareStatement(query1)){
// pst.setString(10, kb);
pst.setString(1, ((JTextField) jDate1.getDateEditor().getUiComponent()).getText());
pst.setString(2, kc);
pst.setDouble(3, ks);
pst.setDouble(4, kt);
pst.setDouble(5, ku);
pst.setString(6, kj);
pst.setString(7, kk);
pst.setDouble(8, kv);
pst.setDouble(9, kw);
pst.execute();
}
try {
int rows = jTable2.getRowCount();
for (int row = 0; row < rows; row++) {
String kd = (String) jTable2.getValueAt(row, 0);
Double kn = (Double) jTable2.getValueAt(row, 1);
try {
// Class.forName("com.mysql.jdbc.Driver").newInstance();
// Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/canning?zeroDateTimeBehavior=convertToNull", "root", "");
String query = "insert into production(product_name,product_quantity)"
+ "values (?,?)";
PreparedStatement update = con.prepareStatement(query);
update.setString(1, kd);
update.setDouble(2, kn);
update.addBatch();
update.executeBatch();
con.commit();
} catch (SQLException e) {
e.printStackTrace();
// JOptionPane.showMessageDialog(this, "Error in production Table");
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Invalid Entry in fields");
}
} catch (Exception e) {
e.printStackTrace();
// JOptionPane.showMessageDialog(null, "Invalid in fields");
}
} catch (Exception e) {
e.printStackTrace();
}
你有沒有嘗試用調試器運行你的代碼,以便知道哪個對象爲空?此外,嘗試使用顯式變量名稱,在當前狀態下,您的代碼根本不可讀取。 – SebVb
我使用了一個調試器,它表明問題出在我的for循環中,但我沒有看到任何錯誤,是嗎? – Stevoski