SQL语句参数化
SQL注入
用户提交带有恶意的数据与SQL语句进行字符串方式的拼接,从而影响SQL语句的语义,最终产生数据泄露的现象
代码演示示例
# 导入pymysql包
import pymysql
# 创建连接对象
conn = pymysql.connect(host='localhost', port=3306, user='root', password='1234',database='python_test_1', charset='utf8')
# 获取游标对象
cur = conn.cursor()
# 不安全的方式
# 根据id查询学生信息
find_name = input('请输入您要查询的学生姓名:') # 如果输入 ' or 1 or' 将会发生SQL注入,查询出全部数据
sql = "select * from students where name='%s'" % find_name # "select * from students where name='' or 1 or''"
# 显示所有数据
cur.execute(sql) # 受影响的行数
content = cur.fetchall() # 从上一次读取数据的位置开始读
for i in content:
print(i)
# 关闭游标和连接
cur.close()
conn.close()
如何防止SQL注入
SQL语句参数化
- SQL语句中的参数使用%s来占位,此处不是python中的字符串格式化操作
- 将SQL语句中%s占位所需要的参数存在一个列表中,把参数列表传递给execute方法中的第二个参数
安全方式
- 构造参数列表:
params = [find_name]
- 执行select语句:
sql = "select * from students where name=%s"
这里的%s不需要加引号cur.execute(sql, params)
# 导入pymysql包
import pymysql
# 创建连接对象
conn = pymysql.connect(host='localhost', port=3306, user='root', password='1234',database='python_test_1', charset='utf8')
# 获取游标对象
cur = conn.cursor()
# 安全的方式
# 根据id查询学生信息
find_name = input('请输入您要查询的学生姓名:')
sql = "select * from students where name=%s"
# 显示所有数据
cur.execute(sql, [find_name]) # 受影响的行数
content = cur.fetchall() # 从上一次读取数据的位置开始读
for i in content:
print(i)
# 关闭游标和连接
cur.close()
conn.close()