String sql2="if not exists(select * FROM stock where productCode=?)\n" +
"Begin\n" +
"insert into stock "
+ "(productName,quantity,currentQuantity,price,companyName,categoryName,productCode) "
+ "values(?,?,?,?,?,?,?)\n" +
"End";
PreparedStatement pst2 = con.prepareStatement(sql2);
pst2.setString(1,productCodeTextField.getText());
pst2.setString(2,productNameTextField.getText());
pst2.setString(3,quantityTextField.getText());
pst2.setString(4,quantityTextField.getText());
pst2.setString(5,priceTextField.getText());
pst2.setString(6, (String) companyNameJComboBox.getSelectedItem());
pst2.setString(7, (String) categoryNameJComboBox.getSelectedItem());
pst2.setString(8,productCodeTextField.getText());
int x=pst2.executeUpdate();
if(x!=0){
productCodeTextField.setText("");
productNameTextField.setText("");
quantityTextField.setText("");
priceTextField.setText("");
JOptionPane.showMessageDialog(null,"Product entered");
}else{
JOptionPane.showMessageDialog(null,"Product already exists");
}
我在插入之前已成功检查现有产品,但我无法根据执行的查询填充正确的消息。即使没有插入,executeUpdate也总是返回一些值。如何解决这个问题。
答案 0 :(得分:1)
有一个更简单的解决方案可能适合您:
丢弃检查条目是否已存在的第一个查询
重写sql2如下:
INSERT INTO stock
(productCode, productName, quantity, price, companyName, categoryName)
VALUES (?,?,?,?,?,?)
WHERE NOT EXISTS
(SELECT * FROM stock WHERE productCode = ?)
添加:pst.setString(7, productCodeTextField.getText());
executeUpdate()
返回int
,表示受查询影响的行数。使用此变量可确定是否添加了行。如果变量!= 0显示成功消息。
答案 1 :(得分:0)
INSERT INTO stock
(productCode, productName, quantity, price, companyName, categoryName)
select ?,?,?,?,?,?
WHERE NOT EXISTS
(SELECT * FROM stock WHERE productCode = ?)
这是SQL Server的工作方式。与Coop回答的3分和4分