解决方案
-
有些网站在让其输入账号的时候,会自动检测,不能输入特殊字符
-
在程序中更改字符串拼接的方式
改写为(execute 帮我们做字符串拼接,我们无需且一定不能再为%s加引号了)sql = 'select id, username, password from userinfo where username=%(uname)s and password=%(pwd)s;' # 再次提醒一下,用execute的args形式传参,原sql字符串中的占位符就无需且不能再加引号了。 cursor.execute(query=sql, args={'uname': username, 'pwd': password}) # ======================================================================= # args用哪种形式,具体看格式化怎么写 # 'select id, username, password from userinfo where username=%s and password=%s;' # 1. cursor.execute(query=sql, args=(username, password, )) # 2. cursor.execute(query=sql, args=[username, password, ]) # # 'select id, username, password from userinfo where username=%(uname)s and password=%(pwd)s;' # 3. cursor.execute(query=sql, args={'uname': username, 'pwd': password}) # =============================================================================================
示例代码
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""sql注入解决方案
1. 有些网站在让其输入账号的时候,会自动检测,不能输入特殊字符
2. 在程序中更改字符串拼接的方式
改写为(execute帮我们做字符串拼接,我们无需且一定不能再为%s加引号了)
"""
import pymysql
# 连接
conn = pymysql.connect(
user='root',
password='',
host='localhost',
port=3306,
charset='utf8mb4',
database='hardy2_db',
)
cursor = conn.cursor(cursor=None)
username = input('username, please>>> ').strip()
password = input('password, please>>> ').strip()
try:
sql = 'select id, username, password from userinfo where username=%(uname)s and password=%(pwd)s;'
# 再次提醒一下,用execute的args形式传参,原sql字符串中的占位符就无需且不能再加引号了。
cursor.execute(query=sql, args={'uname': username, 'pwd': password})
# =======================================================================
# args用哪种形式,具体看格式化怎么写
# 'select id, username, password from userinfo where username=%s and password=%s;'
# 1. cursor.execute(query=sql, args=(username, password, ))
# 2. cursor.execute(query=sql, args=[username, password, ])
#
# 'select id, username, password from userinfo where username=%(uname)s and password=%(pwd)s;'
# 3. cursor.execute(query=sql, args={'uname': username, 'pwd': password})
# =============================================================================================
res = cursor.fetchone()
except pymysql.err.ProgrammingError as e:
print(e)
except pymysql.err.InternalError as e:
print(e)
else:
if res:
print('Welcome to log in!')
else:
print('Failed!')
finally:
# 关闭游标
cursor.close()
# 关闭连接
conn.close()