简体   繁体   English

无法从 MySQL 数据库中删除记录

[英]Can't delete record from MySQL database

Trying to delete record from my database, but I get the error "Unknown column '' in 'where clause'".试图从我的数据库中删除记录,但我收到错误“'where 子句'中的未知列'”。

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:想象一下有人在tfemail字段中输入以下文本:

"Joe' OR FALSE"

and let's see what that would do to your SQL query:让我们看看这会对您的 SQL 查询产生什么影响:

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

bye, database!再见,数据库!

Some dbs let you execute stuff on the server the db engine runs on.一些 dbs 允许您在运行 db 引擎的服务器上执行一些东西。 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.这也意味着需要删除您的executeQuery方法 - 抽象('这里有一些 SQL,请运行它')很少有用(因为它不能包含任何用户输入),并诱使您编写安全漏洞。

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");这解决了您的问题,并且安全地解决了 - 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").现在不再是问题(DB 引擎或 JDBC 驱动程序保证它会解决问题;效果将是删除用户表中字面上读取“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.解决方案是例如 bcrypt:使用专门设计用于存储密码的散列算法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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