1、注入问题
(1)假设有登录案例SQL语句如下:
SELECT * FROM 用户表 WHERE NAME = 用户输入的用户名 AND PASSWORD = 用户输的密码;
(2)此时,当用户输入正确的账号与密码后,查询到了信息则让用户登录;
(3)但是当用户输入的账号为XXX 密码为:XXX' OR ‘a’=’a时,则真正执行的代码变为:
SELECT * FROM 用户表 WHERE NAME = ‘XXX’ AND PASSWORD =’ XXX’ OR ’a’=’a’;
(4)此时,上述查询语句时永远可以查询出结果的。那么用户就直接登录成功了,显然我们不希望看到这样的结果,这便是SQL注入问题。
2、案例演示
(1)创建表
CREATE TABLE users( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(100), PASSWORD VARCHAR(100) );
(2)插入数据
INSERT INTO users (username,PASSWORD) VALUES ('a','1'),('b','2');
(3)查询表数据
SELECT * FROM users;
(4)登录查询
①正常查询
SELECT * FROM users WHERE username='a' AND PASSWORD='1'
②账号随意写,1=1为true
SELECT * FROM users WHERE username='dsfsdfd' AND PASSWORD='wrethiyu' OR 1=1
(5)代码演示
1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.ResultSet; 4 import java.sql.Statement; 5 import java.util.Scanner; 6 7 public class JDBCDemo2 { 8 public static void main(String[] args) throws Exception { 9 Class.forName("com.mysql.jdbc.Driver"); 10 String url = "jdbc:mysql://localhost:3306/mybase"; 11 String username = "root"; 12 String password = "root"; 13 Connection con = DriverManager.getConnection(url, username, password); 14 Statement stat = con.createStatement(); 15 16 Scanner sc = new Scanner(System.in); 17 String user = sc.nextLine(); 18 String pass = sc.nextLine(); 19 20 // 执行SQL语句,数据表,查询用户名和密码,如果存在,登录成功,不存在登录失败 21 // String sql = 22 // "SELECT * FROM users WHERE username='dsfsdfd' AND PASSWORD='wrethiyu' OR 1=1"; 23 String sql = "SELECT * FROM users WHERE username='" + user 24 + "' AND PASSWORD='" + pass + "'"; 25 System.out.println(sql); 26 ResultSet rs = stat.executeQuery(sql); 27 while (rs.next()) { 28 System.out.println(rs.getString("username") + " " 29 + rs.getString("password")); 30 } 31 32 rs.close(); 33 stat.close(); 34 con.close(); 35 } 36 }
运行结果: