如果用户输入添加或删除,我尝试更新我的股票价值。
我的代码在添加和删除后运行,但会使用附加值进行更新。
我的更新只运行SQL。我尝试创建另一个preparedstatement
但它没有用。代码如下,我使用的是java Netbeans。
private void Update_btnActionPerformed(java.awt.event.ActionEvent evt) {
if (txt_add.getText().equals("") && txt_delete.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Enter Stock value");
} else {
String url = "jdbc:sqlserver://localhost:1433;databaseName=InventoryTrackdb";
String un = "sa";
String pass = "123";
PreparedStatement pst = null;
Connection conn = null;
try {
conn = DriverManager.getConnection(url, un, pass);
int pv = Integer.parseInt((Table_stock.getValueAt(Table_stock.getSelectedRow(), 3).toString()));
int value;
int value1;
if (txt_add.getText().equals("")) {
value = 0;
} else {
value = Integer.parseInt(txt_add.getText());
}
if (txt_delete.getText().equals("")) {
value1 = 0;
} else {
value1 = Integer.parseInt(txt_delete.getText());
}
int fv = pv + value;
int fv1 = pv - value1;
if (fv1 < 0) {
JOptionPane.showMessageDialog(null, "Negative Stock");
clear_text();
}
else {
String sql = "Update Add_item set Stock = '" + fv + "' where Itemcode = '" + txt_id.getText()
+ "' and Itemname = '" + txt_name.getText() + "' ";
String sql1 = "Update Add_item set Stock = '" + fv1 + "' where Itemcode = '" + txt_id.getText()
+ "' and Itemname = '" + txt_name.getText() + "' ";
pst = conn.prepareStatement(sql1);
pst.executeUpdate();
pst = conn.prepareStatement(sql);
pst.executeUpdate();
update_table();
JOptionPane.showMessageDialog(null, "Updated Successfully");
clear_text();
}
}
catch (SQLException ex) {
Logger.getLogger(Main_stock.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
以下是该页面的图片:
答案 0 :(得分:0)
您必须使用PreparedStatement来避免语法错误或SQL注入,在您的情况下,最好还使用批处理,如下所示:
String sql = "Update Add_item set Stock = ? where Itemcode = ? and Itemname = ?";
try (PreparedStatement pstmt = connection.prepareStatement(sql);) {
pstmt.setString(1, fv);
pstmt.setString(2, txt_id.getText());
pstmt.addBatch();//First Batch
pstmt.setString(1, fv1);
pstmt.setString(2, txt_id.getText());
pstmt.addBatch();//Second batch
int[] result = pstmt.executeBatch();//Submits both batch of commands to the database
}