SQL注入
什么是SQL注入
防止SQL注入
模拟注入语句
sql = "select * from students where id = 1 or 1 = 1 or '';" # 查
代码示例
if __name__ == '__main__':
# 1.导包
import pymysql
# 2.创建连接对象
conn = pymysql.connect(host="主机地址",
port=3306,
user="root",
password="123456",
database="python",
charset="utf8")
# 3.获取游标,目的就是执行sql语句
cursor = conn.cursor()
# 准备sql,使用防止sql注入的sql语句
# %s:sql语句的参数,和字符串里面的%s不同
sql = "select * from students where name = %s;" # 查
# 4、执行sql语句
cursor.execute(sql, ("梁来福",))
# 获取查询的结果,返回的数据类型是一个元祖
# row = cursor.fetchone()
# print(row)
# 获取结果所有数据
result = cursor.fetchall()
for row in result:
print(row)
# 5.关闭游标
cursor.close()
# 6.关闭连接
conn.close()
防止SQL注入多参数使用
代码示例
# 1.导包
import pymysql
if __name__ == '__main__':
# 2.创建连接对象
conn = pymysql.connect(host="主机地址",
port=3306,
user="root",
password="123456",
database="python",
charset="utf8")
# 3.获取游标,目的就是执行sql语句
cursor = conn.cursor()
# 准备sql
sql = "insert into students(name, age, gender, c_id) value (%s, %s, %s, %s);" # 增
try:
# 4、执行sql语句,传入的参数类型可以是元祖,列表,字典
cursor.execute(sql, ["运气", "88", "男", 2])
# 提交修改的数据到数据库
conn.commit()
except Exception as e:
conn.rollback()
# 获取查询的结果,返回的数据类型是一个元祖
# row = cursor.fetchone()
# print(row)
# 获取结果所有数据
# result = cursor.fetchall()
# for row in result:
# print(row)
# 5.关闭游标
finally:
cursor.close()
# 6.关闭连接
conn.close()