您的位置:首页 > 数据库

mybatis与sql注入

2016-04-22 12:21 357 查看
Recently I was asked about how mybatis prevent sql injection, but I don't know.

Then I searched on the Internet, found something useful about sql injection.

First, Let's look the difference about Statement and PrepareStatement in Java.

If we create a sql like this

String sql = "select * from tb_name where name= ' " + varname + " ' and passwd = ' " + varpasswd + " ' " ;

Statement st = con.createStatement();

And we call the sql is dynamicly collage, If the client send varname and varpasswd are "admin" and" admin' or '1' = '1 ", what's the result of it?

this sql will like this

select * from tb_name where name= 'admin' and passwd = 'admin' or '1' = '1' ;

this is a typically sql injection, it will show all data;

if we use PrepareStatement , will like this:

perstmt=con.prepareStatement("select * from tb_name where name = ? and passwd = ?");

   perstmt.setString(1, var1);

   perstmt.setString(2, var2);

   perstmt.execute();

it PrepareStatement will compile this sql in advance, and when you send the same parameters to it, it will become like this:

select * from tb_name where name= " admin " and passwd = "admin ' or '1' = '1 " ;

It sql will treate the wholeadmin' or '1' = '1 as
passwd ,

This is only becausePrepareStatement compile this sql in advance , and when you send parameters
to it,

it will only replace the ? ,and prevent the sql injection.

it means that
PrepareStatement compile the whole sql and only let you set the parameter to it as whole.

And mybatis , if we make like this

<select id ="getBlog" resultType="Blog" parameterType="int">

select * from blog where id= #{id}

</select>

when you see the log no matter what parameter you sent it , it will print

select * from blog where id = ?

in fact, it compile in advance ,it uses PrepareStatement to prevent sql injection.

But under some condictions, like the name of the table, the name of the column is parameter,is dynamctic, we must make it like this

<select id ="getBlog" resultType="Blog" parameterType="int">

select * from ${blog}

</select>

when you see the log when you pass "blog" to it, it will print

select * from blog

and in this case, it send parament directly to this sql ,can't prevent sql injection.


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: