2012-02-25 9 views
6

Posso cancellare un intero con successo ma quando ho provato a renderlo un STRING si dice "articolo sconosciuto colonna in clausola where ma il mio ITEMTODELETE è un STRING dichiarato nel database non ? un intero quanto non elimina uno STRINGCome eliminare un record (stringa) JAVA e MYSQL

sotto è il mio codice:

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

risposta

6

provare a cambiare la linea:

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

al

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

grazie! Ora funziona :) – mix

0

penso che è necessario passare Integer.parseInt(id) e non id ... supponendo che il id è int

5

non utilizzare un Statement utilizzare un PreparedStatement invece, in caso contrario la vostra applicazione sarà vulnerabile a iniezioni SQL. Per esempio. qualcuno entra in una stringa del tipo: "'; drop table inventory; --"

La corrispondente statment preparato sarebbe simile:

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(); 
Problemi correlati