JavaWeb开发sql注入详细实例讲解

一、在数据库中插入一条用户记录

二、用mysql-connector-java-5.1.15-bin.jar连接数据库。

创建返回数据库conn连接的类Db

package com.mysql.zhang;
import java.sql.Connection;
import java.sql.DriverManager;
public class Db {	
private Db() {	
};
private static Connection conn=null;
public static Connection getConn() {
	try {
		String password="root";
		String user="root";
		String url="jdbc:mysql://localhost:3306/test";	
		Class.forName("com.mysql.jdbc.Driver");
		conn=DriverManager.getConnection(url, user, password);
	} catch (ClassNotFoundException e) {
		e.printStackTrace();
	} catch (Exception e) {	
		e.printStackTrace();
	}
	return conn;	
   }
}
测试类

package com.mysql.zhang;

import java.sql.Connection;
import java.sql.PreparedStatement;
public class Test {
public static void main(String[] args) throws Exception {
    Connection conn=Db.getConn();    
    String sql = "select *from user where name= 'shuibianxie' and password='or1=1'";  
    //name值可以随便写
    PreparedStatement pt=conn.prepareStatement(sql);
    System.out.println( "返回查询结果bool值:"+pt.execute());
    conn.close();
    }
}

三、String sql = "select *from user where name= 'shuibianxie' and password='or1=1'";  

由于数据库缺陷导致这条语句是恒等的,所以返回true。

试想想一下,如果一个人在用户登录页面表单中用户名随便输入

密码输入or1=1  并且你在服务器中拼接sql语句,依靠返回的boolean值( pt.execute() )判断用户是否登录成功。

那么就会导致不用数据库中存在的用户名+密码就能够登录成功。

猜你喜欢

转载自blog.csdn.net/Boxzhang/article/details/82706085