当前位置:网站首页>JDBC 预防sql注入问题与解决方法[PreparedStatement]
JDBC 预防sql注入问题与解决方法[PreparedStatement]
2022-07-02 09:43:00 【心态还需努力呀】
前言
为演示预防sql注入问题,我们使用用户登录输入用户名和密码来说明问题和解决问题。
数据库表如图:
一、问题解释
先用常用的Statement
String name="tom";
// String psw="123456";
String psw="' or '1'='1";
// 解决问题前
// 3.定义sql
String sql="SELECT * FROM user_info where name='"+name+"' and password='"+psw+"'";
Statement stmt= (Statement) conn.createStatement();
//5.执行sql
ResultSet rs = stmt.executeQuery(sql);
登录判断代码
if(rs.next()){
System.out.println("登陆成功~");
}else{
System.out.println("登陆失败~");
}
如果密码为' or '1'='1 ,执行结果
我们会发现,数据库表tom的密码不是 ' or '1'='1,但可以登录成功!这是为什么?
我们打印下sql语句分析原因
System.out.println(sql);
运行结果
这里我们可以看where条件:name=‘tom’为真 password=‘’为假 ‘1’=‘1’为真。
可以判断 真 and 假 or 真 =(假 or 真)=真。结果永远为真,所以可以登录成功!
但怎么解决这个问题呢!!!如果这用都可以随意登录别人的账号了。
二、解决方法
我们只需要使用PreparedStatement解决 将敏感字符进行转义
代码:
String sql="select * from user_info where name=? and password=?";
PreparedStatement pstmt=conn.prepareStatement(sql);
pstmt.setString(1,name);
pstmt.setString(2,psw);
ResultSet rs=pstmt.executeQuery();
现在的运行结果
这里使用密码为' or '1'='1 就不会显示登录成功。这是为什么呢?
先看上述sql输出的select * from user_info where name=? and password=?
它是先将敏感字符进行转义
把' or '1'='1 转义字符\' or \'1\'=\'1 变成了文本形式 所以sql语句会找不到结果
这样就解决了sql注入的问题
总结
这个也是后期自己做项目时需要注意的问题,PreparedStatement的使用知识点,不然的话会被恶意登录。
边栏推荐
- Redis avalanche, penetration, breakdown
- [ybtoj advanced training guidance] cross the river [BFS]
- Docker compose configuration mysql, redis, mongodb
- Input a three digit number and output its single digit, ten digit and hundred digit.
- Leetcode122 the best time to buy and sell stocks II
- 堆(優先級隊列)
- Find the common ancestor of any two numbers in a binary tree
- Lekao: 22 year first-class fire engineer "technical practice" knowledge points
- Map and set
- 包管理工具
猜你喜欢
ThreadLocal的简单理解
Win10 system OmniPeek wireless packet capturing network card driver failed to install due to digital signature problem solution
刷题---二叉树--2
Lekao.com: experience sharing of junior economists and previous candidates in customs clearance
Find the common ancestor of any two numbers in a binary tree
VLAN experiment
Deep understanding of P-R curve, ROC and AUC
Anti shake throttle
arcgis js 4. Add pictures to x map
2.6 using recursion and stack - [tower of Hanoi problem]
随机推荐
Map and set
Leetcode209 subarray with the smallest length
Drools dynamically add, modify, and delete rules
Input a three digit number and output its single digit, ten digit and hundred digit.
[C language] Yang Hui triangle, customize the number of lines of the triangle
BOM DOM
LeetCode—剑指 Offer 51. 数组中的逆序对
Go学习笔记—基于Go的进程间通信
高性能纠删码编码
BOM DOM
记录一下MySql update会锁定哪些范围的数据
Bom Dom
Post request body content cannot be retrieved repeatedly
Leetcode122 the best time to buy and sell stocks II
Leetcode - Sword finger offer 59 - I, 59 - II
刷题---二叉树--2
drools中then部分的写法
Calculate the maximum path sum of binary tree
线性DP AcWing 898. 数字三角形
Sub thread get request