2012-02-25 8 views
6

Pomyślnie można usunąć liczbę całkowitą, ale gdy próbowałem zrobić to STRING, mówi "nieznana kolumna itemtodelete w klauzuli where, ale mój ITEMTODELETE jest STRING zadeklarowany w bazie danych nie ? liczbą całkowitą ile nie usuwa ciągJak usunąć rekord (ciąg) JAVA i MYSQL

poniżej jest mój kod:

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

Odpowiedz

6

spróbuj zmienić linię:

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

do

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

dziękuję! Teraz działa :) – mix

0

myślę, że trzeba zdać Integer.parseInt(id) i nie id ... Zakładając, że id jest int

5

Nie używaj Statement użyć PreparedStatement zamiast, w przeciwnym razie aplikacja będzie podatny na SQL injection. Na przykład. ktoś wejdzie ciąg jak: "'; drop table inventory; --"

Odpowiedni przygotowany statment będzie wyglądać następująco:

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(); 
Powiązane problemy