什么是sql注入,怎么防止SQL注入?

防止SQL注入

什么是SQL注入?

  • 用户提交带有恶意的数据与SQL语句进行字符串方式的拼接,从而影响了SQL语句的语义,最终产 生数据泄露的现象

如何防止SQL注入?
SQL语句参数化

  • SQL语言中的参数使用%s来占位,此处不是python中的字符串格式化操作
  • 将SQL语句中%s占位所需要的参数存在一个列表中,把参数列表传递给execute方法中第二个参数

防止SQL注入的示例代码:

from pymysql import connect
def main():
find_name = input("请输⼊物品名称:")
# 创建Connection连接
conn = connect(host='localhost',port=3306,user='root',password='mysql',data
base='jing_dong',charset='utf8')
# 获得Cursor对象
cs1 = conn.cursor()
# ⾮安全的⽅式
# 输⼊ ' or 1 = 1 or ' (单引号也要输⼊)
# sql = "select * from goods where name='%s'" % find_name
# print("""sql===>%s<====""" % sql)
# # 执⾏select语句,并返回受影响的⾏数:查询所有数据
# count = cs1.execute(sql)
# 安全的⽅式
# 构造参数列表
params = [find_name]
# 执⾏select语句,并返回受影响的⾏数:查询所有数据
count = cs1.execute("select * from goods where name=%s", params)
# 注意:
# 如果要是有多个参数,需要进⾏参数化
# 那么params = [数值1, 数值2....],此时sql语句中有多个%s即可
# %s 不需要带引号
# 打印受影响的⾏数
print(count)
# 获取查询的结果
# result = cs1.fetchone()
result = cs1.fetchall()
# 打印查询的结果
print(result)
# 关闭Cursor对象
cs1.close()
# 关闭Connection对象
conn.close()
if __name__ == '__main__':
main()

说明:

  • execute方法中的 %s 占位不需要带引号
发布了58 篇原创文章 · 获赞 14 · 访问量 9381

猜你喜欢

转载自blog.csdn.net/lh_hebine/article/details/98973796