JDBC之Sql注入问题
用户输入的数据包括sql关键字或者语法,导致sql查询时where后面的条件固定为true
sql注入的语法
案例
package com.qf.JDBC;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
public class TestJDBC2 {
public static void main(String[] args) throws Exception{
//1,注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获得连接
String url="jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC";
String user="root";
String password = "123456";
Connection connection = DriverManager.getConnection(url,user,password);
if(connection==null){
System.out.println("连接失败");
}else{
System.out.println("连接成功");
}
System.out.println("sql注入语法:");
System.out.println("abc' or 1=1;#");
Scanner scanner = new Scanner(System.in);
System.out.println("请输入名字:");
String name = scanner.nextLine();//next遇到空格结束,nextline能读取空格
System.out.println("请输入钱数:");
String money = scanner.nextLine();
//3.获得执行Sql语句的对象
Statement statement = connection.createStatement();
//4.执行查询语句(这里被sql注入),sql注入后不需要正确的数据仍能进行查询操作.
//sql注入,用户输入的数据包括sql关键字或者语法,导致编译后where后的条件为true
//String sql = "select * from accounts where name='A' and money='1000'";
String sql = "select * from accounts where name='"+name+"' and money='"+money+"'";
ResultSet resultSet = statement.executeQuery(sql);
if (resultSet.next()){
System.out.println("登陆成功");
}else{
System.out.println("登录失败");
}
while (resultSet.next()){
String id = resultSet.getString(1);//String id = resultSet.getString(id);
String name1 = resultSet.getString(2);
String money2 = resultSet.getString(3);
System.out.println(id+"\t"+name1+"\t"+money2);
}
}
}
输入数据
名字:abc' or 1=1;#
钱数:123123123124142
运行结果
连接成功 sql注入语法: abc' or 1=1;# 请输入名字: abc' or 1=1;# 请输入钱数: 12321314 登陆成功 2 B 1000.0 3 C 1000.0 4 null null 5 null null 6 A 1000.0 7 B 1000.0 8 C 1000.0 10 zht 1234.0 12 zht 1234.0 13 zht 1234.0 14 zht 1234.0
Process finished with exit code 0