有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在JAVA和MYSQL中删除记录(字符串)

我成功地删除了一个整数,但当我试图把它变成一个字符串时,它说 “where子句中的未知列itemtodelete,但我的itemtodelete是数据库中声明的字符串,而不是整数它不删除字符串的程度是多少?”

下面是我的代码:

 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);
        }
    }

共 (3) 个答案

  1. # 1 楼答案

    不要使用Statement而是使用PreparedStatement,否则应用程序将容易受到SQL注入的攻击。例如,某人输入如下字符串:"'; drop table inventory; "

    相应的准备好的状态如下所示:

    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();
    
  2. # 2 楼答案

    我认为你需要通过Integer.parseInt(id)而不是id。。。假设你的idint

  3. # 3 楼答案

    试着换一行:

    String SQL = "DELETE FROM inventory WHERE ItemCode = "+id+" ";
    

    String SQL = "DELETE FROM inventory WHERE ItemCode = '"+id+"' ";