作者:mobiledu2502873611 | 来源:互联网 | 2023-09-15 14:05
SQL注入的定义以及解决
什么是SQL注入
SQL 注入就是在用户输入的字符串中加入 SQL 语句,如果在设计不良的程序中忽略了检查,那么这些注入进去的 SQL 语句就会被数据库服务器误认为是正常的 SQL 语句而运行,攻击者就可以执行计划外的命令或访问未被授权的数据。
说人话就是,程序把用户输入的遍历当作SQL语句的关键字而执行了。
下边给出一个简单的demo:
import java.sql.*;
import java.util.Scanner;import com.mysql.jdbc.Driver;public class SQL_insert {public void solve(){Scanner scanner=new Scanner(System.in);System.out.println("输入id:");String id= scanner.nextLine();System.out.println("输入密码:");String name=scanner.nextLine();Statement statement = null;Connection connection = null;ResultSet set = null;try {Driver driver = new Driver();DriverManager.registerDriver(driver);connection = DriverManager.getConnection("jdbc:mysql://localhost:3305/JAVA_LEARN", "root", "root");statement = connection.createStatement();String DQL = "select * from people where id="+id+" and name="+name;set = statement.executeQuery(DQL);if(set.next()) {System.out.println("登陆成功");}else {System.out.println("登陆失败");}} catch (SQLException e) {e.printStackTrace();} finally {if (statement != null) {try {statement.close();} catch (SQLException e) {e.printStackTrace();}}if (connection != null) {try {connection.close();} catch (SQLException e) {e.printStackTrace();}}if (set != null) {try {set.close();} catch (SQLException e) {e.printStackTrace();}}}}public static void main(String[] args) {SQL_insert insert = new SQL_insert();insert.solve();}
}
这是一个简单的登陆检查程序,现在给他一个错误的输入:
显示登陆成功。
为什么会这样?
因为用户输入的密码是 123 or 1=‘1’
所以执行的SQL就是:
select * from people where id= 123 and name = 123 or 1='1'
密码的一部分被当作关键字被编译进去了,所以无论怎么查都会有结果。
如何解决
只要用户输入的信息不参与SQL编译就解决了
只要预先编译SQL语句框架,然后再给SQL传值即可
故引入 PreparedStatement 预编译的数据库操作对象
解决后的demo
import com.mysql.jdbc.Driver;import java.sql.*;
import java.util.Scanner;public class SQL_insert_Solve {public void solve(){Scanner scanner=new Scanner(System.in);System.out.println("输入id:");String id= scanner.nextLine();System.out.println("输入密码:");String name=scanner.nextLine();PreparedStatement statement = null;Connection connection = null;ResultSet set = null;try {Driver driver = new Driver();DriverManager.registerDriver(driver);connection = DriverManager.getConnection("jdbc:mysql://localhost:3305/JAVA_LEARN", "root", "root");statement = connection.prepareStatement("select * from people where id = ? and name = ?");statement.setString(1,id);statement.setString(2,name);set = statement.executeQuery();if(set.next()) {System.out.println("登陆成功");}else {System.out.println("登陆失败");}} catch (SQLException e) {e.printStackTrace();} finally {if (statement != null) {try {statement.close();} catch (SQLException e) {e.printStackTrace();}}if (connection != null) {try {connection.close();} catch (SQLException e) {e.printStackTrace();}}if (set != null) {try {set.close();} catch (SQLException e) {e.printStackTrace();}}}}public static void main(String[] args) {SQL_insert insert = new SQL_insert();insert.solve();}
}