简体   繁体   中英

prepared statement and SQL injection

I have been reading about prepared statement and it said that SQL injection is still very possible with it. Now I would use spring if I was creating an web app but I thought that it allowing such attacks odd.

PreparedStatement forces you to pick the index. 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.

SQL injection attacks are possible with PreparedStatement if you write your SQL like you did where you concatenate your variables to your SQL statement.

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. You can use ?s like I did and then set them programmatically. The values will be properly escaped keeping SQL injection attacks from happening.

Read this to find out how to set the ? values in the SQL like I have written it.

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. Then set the 1-based indexed values and execute the query. 100% safe to SQL-injections!

With Spring, you will probably use a JdbcTemplate. Note there is a NamedParameterJdbcTemplate implementation which does not use indexes, but named parameters. 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!

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