How to delete a record (string) JAVA and MYSQL

I can successfully delete an integer, but when I tried to make it STRING, it says "Unknown itemtodelete column element in where, but my ITEMTODELETE is STRING declared in the database as not integer, how much does it not delete STRING?

below is my code:

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); } } 
+6
source share
3 answers

try changing the line:

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

to

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

DO NOT use Statement instead of PreparedStatement , otherwise your application will be vulnerable to SQL injections. For instance. someone enters a line like: "'; drop table inventory; --"

The corresponding prepared item looks something like this:

 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(); 
+6
source

I think you need to go through Integer.parseInt(id) , not id ... if your id is int

0
source

Source: https://habr.com/ru/post/909333/


All Articles