防止 Java 程序中的 SQL 注入攻击 [英] Prevent SQL injection attacks in a Java program
问题描述
我必须在我的 java 程序中添加一条语句来更新数据库表:
I have to add a statement to my java program to update a database table:
String insert =
"INSERT INTO customer(name,address,email) VALUES('" + name + "','" + addre + "','" + email + "');";
我听说这可以通过 SQL 注入来利用,例如:
I heard that this can be exploited through an SQL injection like:
DROP TABLE customer;
我的程序有一个 Java GUI,所有姓名、地址和电子邮件值都从 Jtextfields
中检索.我想知道黑客如何将以下代码 (DROP TABLE customer;
) 添加到我的插入语句中,以及如何防止这种情况发生.
My program has a Java GUI and all name, address and email values are retrieved from Jtextfields
. I want to know how the following code (DROP TABLE customer;
) could be added to my insert statement by a hacker and how I can prevent this.
推荐答案
您需要使用 PreparedStatement.例如
String insert = "INSERT INTO customer(name,address,email) VALUES(?, ?, ?);";
PreparedStatement ps = connection.prepareStatement(insert);
ps.setString(1, name);
ps.setString(2, addre);
ps.setString(3, email);
ResultSet rs = ps.executeQuery();
这将防止注入攻击.
如果您插入的字符串来自某处的输入,那么黑客将其放入的方式是 - 例如网页上的输入字段,或应用程序中表单上的输入字段或类似内容.
The way the hacker puts it in there is if the String you are inserting has come from input somewhere - e.g. an input field on a web page, or an input field on a form in an application or similar.
这篇关于防止 Java 程序中的 SQL 注入攻击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!