什么是 SQL 注入?
- 利用 SQL 中的一些特殊语法,绕过了 SQL 语句
import pymysql
conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password='xxxxx',
database='练习题',
charset='utf8',
autocommit=True,
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
userid = input('请输入用户名>>>: ').strip()
userpwd = input('请输入密码>>>: ').strip()
sql = "select * from t1 where name='%s' and pwd='%s'" % (userid, userpwd)
cursor.execute(sql)
res = cursor.fetchone()
if res:
print('登录成功')
else:
print('登录失败')
下图是表 t1 中的内容
示例一、
请输入用户名>>>: ly' -- xxxxxx
请输入密码>>>: 333
'在密码错误的情况下仍可成功登录'
将 sql 打印可知
select * from t1 where name='ly' -- xxxxxx' and pwd='333'
而 '-- ' 在 SQL语句中表示注释的意思,因此之后的代码并不执行,直接跳过,因此输入密码已失去意义
如下图
示例二、
请输入用户名>>>: egon ' or 1=1 -- xxxx
请输入密码>>>:
将 sql 打印可知
select * from t1 where name='egon ' or 1=1 -- xxxx' and pwd=''
在账户名输入错误的情况下,使用 or 跳过错错误选项,引用一个恒成立的结果,并跳过密码同样可以达到登录账户的目的
如下图
解决 SQL 注入问题
import pymysql
conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password='xxxxx',
database='练习题',
charset='utf8',
autocommit=True,
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
userid = input('请输入用户名>>>: ').strip()
userpwd = input('请输入密码>>>: ').strip()
sql = "select * from t1 where name='%s' and pwd='%s'"
cursor.execute(sql, (userid, userpwd)) # 使用 pymsql 模块的 excute 语句,并遵循其语法即可过滤特殊符号,解决 SQL 注入问题
res = cursor.fetchone()
if res:
print('登录成功')
else:
print('登录失败')