pymysql模块学习之sql注入解决方案

解决方案

  1. 有些网站在让其输入账号的时候,会自动检测,不能输入特殊字符

  2. 在程序中更改字符串拼接的方式
    改写为(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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值