简体   繁体   中英

Can't delete record from MySQL database

Trying to delete record from my database, but I get the error "Unknown column '' in 'where clause'".

private void deleteUser() {
    String query = "DELETE FROM user WHERE Name =" + tfemail.getText() + "";
    executeQuery(query);
    showUsers();
}

在此处输入图像描述 在此处输入图像描述

You can't write queries this way. Imagine someone put in the tfemail field this text:

"Joe' OR FALSE"

and let's see what that would do to your SQL query:

DELETE FROM user WHERE Name = 'Joe' OR FALSE;

bye, database!

Some dbs let you execute stuff on the server the db engine runs on. Which means this trick can be used to completely hack the machine or format the disk entirely. bye, entire machine.

This also means your executeQuery method needs to be removed - that abstraction ('here is some SQL, please run it') is rarely useful (as it cannot contain any user input), and entices you to write security leaks.

The solution is prepared statements:

PreparedStatement ps = con.prepareStatement("DELETE FROM user WHERE Name = ?");
ps.setString(1, "Joe");
ps.executeUpdate();

This solves your problem, and does so safely - ps.setString(1, "Joe' OR FALSE"); is now no longer an issue (the DB engine or JDBC driver guarantees that it will take care of the problem; the effect would be to delete the entry in your user table that literally reads "Joe' OR FALSE").

Furthermore, storing passwords in a database is not an acceptable strategy; the solution is eg bcrypt: Use a hashing algorithm designed specifically to store passwords.

String query = "DELETE FROM user WHERE Name ='" + tfemail.getText() + "'"; ^ ^ |___________add___________|

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM