简体   繁体   English

预备语句和SQL注入

[英]prepared statement and SQL injection

I have been reading about prepared statement and it said that SQL injection is still very possible with it. 我一直在阅读有关准备好的语句的信息,它说SQL注入仍然非常有可能。 Now I would use spring if I was creating an web app but I thought that it allowing such attacks odd. 现在,如果要创建Web应用程序,我会使用spring,但我认为它允许此类攻击很奇怪。

PreparedStatement forces you to pick the index. PreparedStatement强制您选择索引。 This will cause many problems because you will not always want to pick the same location over and over to store data. 这将引起很多问题,因为您将不总是要反复选择相同的位置来存储数据。 Even if you create a counter it will be counter productive because it will reset everything the program shuts down. 即使您创建一个计数器,它也会适得其反,因为它将重置程序关闭的所有内容。

String query = "INSERT INTO offers (name,email.text) VALUES 
'"+name+"','"+email+ "','"+text+"'";

Lets say the above code is my query. 可以说上面的代码是我的查询。 What is a safe alternative and will allow auto increment in the mySQL database. 什么是安全的替代方法,它将允许在mySQL数据库中自动递增。

SQL injection attacks are possible with PreparedStatement if you write your SQL like you did where you concatenate your variables to your SQL statement. 如果像在将变量连接到SQL语句的方式编写SQL一样编写SQL,则使用PreparedStatement可能会发生SQL注入攻击。

Your query should be 您的查询应为

String query = "INSERT INTO offers (name,email,text) VALUES (?,?,?)

By concatenating the values like you did you are indeed allowing the possibility of sql injection because the values of those variables could be actual SQL which would cause your insert to do something that is not intended. 通过像您那样串联这些值,您确实允许进行sql注入,因为这些变量的值可能是实际的SQL,这将导致您的插入执行不想要的操作。 You can use ?s like I did and then set them programmatically. 您可以像我一样使用?s,然后以编程方式设置它们。 The values will be properly escaped keeping SQL injection attacks from happening. 这些值将正确转义,以防止发生SQL注入攻击。

Read this to find out how to set the ? 阅读本文以了解如何设置? values in the SQL like I have written it. SQL中的值,就像我写的一样。

Using Prepared Statements 使用准备好的语句

A prepared statement query will be something like this: 准备好的语句查询将如下所示:

String sql = "insert into offers (name, email, text) values(?, ?, ?);

You the create a PreparedStatement with this. 您用此创建一个PreparedStatement。 Then set the 1-based indexed values and execute the query. 然后设置基于1的索引值并执行查询。 100% safe to SQL-injections! SQL注入100%安全!

With Spring, you will probably use a JdbcTemplate. 使用Spring,您可能会使用JdbcTemplate。 Note there is a NamedParameterJdbcTemplate implementation which does not use indexes, but named parameters. 请注意,存在一个NamedParameterJdbcTemplate实现,该实现不使用索引,而是使用命名参数。 Query will be: 查询将是:

String sql = "insert into offers (name, email, text) values(:name, :email, :text);

Then set the name-based values and execute the query. 然后设置基于名称的值并执行查询。 Again 100% safe to SQL-injections! 同样,SQL注入100%安全!

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

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