我在Java Swing sql项目中编码。我一直坚持删除和更新信息记录。我可以正常添加一条新记录,但不能更新或删除一条记录。当我删除时,它将通知“找不到列号”。这是我的代码和错误消息的图片。预先感谢。
private void JtbDeleteActionPerformed(java.awt.event.ActionEvent evt) {
int row = jtbStudent.getSelectedRow();
String cell = jtbStudent.getModel().getValueAt(row, 0).toString();
try {
stm = cnn.createStatement();
if (JOptionPane.showConfirmDialog(null, "Are you sure?", "WARNING",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
stm.execute("DELETE FROM Student where RollNo = " + cell);
loadTable();
JOptionPane.showMessageDialog(null, "Delete Successfully");
} else {
JOptionPane.showMessageDialog(null, "Delete Unsuccesfully!");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
finally{
try {
stm.close();
rs.close();
} catch (Exception e) {
}
}
}
更新按钮
private void jbtUpdateActionPerformed(java.awt.event.ActionEvent evt) {
try {
int row = jtbStudent.getSelectedRow();
String cell = jtbStudent.getModel().getValueAt(row, 0).toString();
stm = cnn.createStatement();
String value1 = jtxName.getText();
String value2 = jtxMark.getText();
String sql="UPDATE Student set Name='"+value1+"' ,mark='"+value2+"'
,where RollNo = '" + cell + "'";
stm.execute(sql);
System.out.println("Update success!");
loadTable();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
答案 0 :(得分:2)
您正在使用无效的SQL语句。您正在写(并发送到数据库)的行是DELETE FROM Student where RollNo = A02
。
您期望的结果(在有效的SQL中)为:DELETE FROM Student where RollNo = 'A02'
。
现在为简单起见,您可以使用
stm.execute("DELETE FROM Student where RollNo = '" + cell + "'");
但这将对SQL注入开放,这意味着如果变量cell
中的String可以读取类似"'; drop table student;"
的内容,那么您的数据库将删除students表。
最好使用准备好的语句(https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html):
PreparedStatement stm = cnn.prepareStatement("DELETE FROM Student where RollNo = ?");
stm.setString(1, cell);
boolean result = stm.execute();
这样,String
被正确地转义了。有关详细信息,请参考jdbc的文档。
PreparedStatement-https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html 连接-https://docs.oracle.com/javase/7/docs/api/java/sql/Connection.html#prepareStatement(java.lang.String)