SQL注入介绍

二、SQL注入范例


这里我们根据用户登录页面

<form action="" > 用户名:<input type="text" name="username"><br/> 密 码:<input type="password" name="password"><br/> </form>
预先创建一个表:

create table user_table( id int Primary key, username varchar(30), password varchar(30) );
insert into user_table values(1,'xiazdong-1','12345'); insert into user_table values(2,'xiazdong-2','12345');
一般查询数据库的代码如下:

public class Demo01 { public static void main(String[] args) throws Exception { String username = "xiazdong"; String password = "12345"; String sql = "SELECT id FROM user_table WHERE " + "username='" + username + "'AND " + "password='" + password + "'"; Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","12345"); PreparedStatement stat = con.prepareStatement(sql); System.out.println(stat.toString()); ResultSet rs = stat.executeQuery(); while(rs.next()){ System.out.println(rs.getString(1)); } } }

但是这里username=xiazdong,password=12345,

因此此处的SQL语句为:


SELECT id FROM user_table WHERE username='xiazdong' AND password='12345';

如果我们把username和password的值变为:

username=' OR 1=1 --
password=x

会变成一个很可怕的情况:将把数据库中所有用户都列出来,为什么呢?

因为SQL语句现在为:

SELECT id FROM user_table WHERE username='' OR 1=1 -- ' AND password='12345';

SELECT id FROM user_table WHERE username='' OR 1=1 -- ' AND password='12345';

因为--表示SQL注释,因此后面语句忽略;

因为1=1恒成立,因此 username='' OR 1=1 恒成立,因此SQL语句等同于:

SELECT id FROM user_table;

很奇妙吧....


三、解决方法


其实解决方法很简单,就是使用PreparedStatement即可;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值