如何删除java中选中的MySQL数据库记录(行)

时间:2017-09-26 06:22:50

标签: java mysql

如何删除MySQL数据库所选记录(行) 我用这个代码

connectDB();
try{
    java.sql.PreparedStatement stmt = con.prepareStatement("DELETE FROM tbl_codes WHERE No=? ");
    String sql = "Delete FROM user WHERE No= "+txt_search_code.getText(); 
    pstmt = con.prepareStatement(sql);
    pstmt.setString(1,txt_search_code.getText());
    pstmt.execute();
    JOptionPane.showMessageDialog(null, " Your new records Deleted Succsessfully!!");   
} catch(Exception e){
    JOptionPane.showMessageDialog(null,e);
}
closeDB();

但是会出现这样的错误 -

  

java.sql.SQLException:参数索引超出范围(1>数   参数,即0)

那么如何解决这个问题......(请举例) 感谢

2 个答案:

答案 0 :(得分:2)

试试这个:

connectDB();
try{
    java.sql.PreparedStatement stmt = con.prepareStatement("DELETE FROM tbl_codes WHERE No=? ");
    stmt.setString(1,txt_search_code.getText());
    stmt.execute();
    JOptionPane.showMessageDialog(null, " Your new records Deleted Succsessfully!!");   
} catch(Exception e){
    JOptionPane.showMessageDialog(null,e);
}
closeDB();

答案 1 :(得分:1)

问题是您没有在要删除的字符串周围使用引号。

应该如下:

string sql = "Delete FROM user WHERE No= '" + txt_search_code.getText()+ "'";

Sql现在正在转换为数字。