如何在JAVA和MYSQL中删除记录(字符串)
我成功地删除了一个整数,但当我尝试将其设置为字符串时,它会显示 “where子句中的未知列itemtodelete,但我的itemtodelete是数据库中声明的字符串,而不是整数它不删除字符串的程度如何?” 下面是我的代码:如何在JAVA和MYSQL中删除记录(字符串),java,Java,我成功地删除了一个整数,但当我尝试将其设置为字符串时,它会显示 “where子句中的未知列itemtodelete,但我的itemtodelete是数据库中声明的字符串,而不是整数它不删除字符串的程度如何?” 下面是我的代码: private void DeleteButtonActionPerformed(java.awt.event.ActionEvent evt) { int del
private void DeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
int del = (prompt):
if (del == JOptionPane.YES_OPTION){
DelCurRec();
}
}
public void DelCurRec() {
String id = field.getText();
String SQL = "DELETE FROM inventory WHERE ItemCode = "+id+" ";
try {
Class.forName(connectio);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE);
}
Statement stmt = null;
Connection con = null;
//Creates connection to database
try {
con = DriverManager.getConnection("Connection");
stmt = con.createStatement();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE);
}
//Execute the SQL statment for deleting records
try {
stmt.executeUpdate(SQL);
//This closes the connection to the database
con.close();
//This closes the dialog
JOptionPane.showMessageDialog(null,"Deleted Succesfully","Delete Successful",JOptionPane.WARNING_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE);
}
}
尝试更改行:
String SQL = "DELETE FROM inventory WHERE ItemCode = "+id+" ";
到
我认为您需要传递
Integer.parseInt(id)
而不是id
…假设您的id
是int不要使用语句
而是使用PreparedStatement
,否则您的应用程序将容易受到SQL注入的攻击。例如,有人输入一个字符串,如:”;下表库存--“
相应的准备好的状态看起来像:
String SQL = "DELETE FROM inventory WHERE ItemCode = ? ";
PreparedStatement pstmt = null;
// get a connection and then in your try catch for executing your delete...
pstmt = con.prepareStatement(SQL);
pstmt.setString(1, id);
pstmt.executeUpdate();
String SQL = "DELETE FROM inventory WHERE ItemCode = ? ";
PreparedStatement pstmt = null;
// get a connection and then in your try catch for executing your delete...
pstmt = con.prepareStatement(SQL);
pstmt.setString(1, id);
pstmt.executeUpdate();