python-pymysql防止sql注入攻击介绍

pymysql

pymysql 是一个第三方模块,帮我们封装了 建立表/用户认证/sql的执行/结果的获取

import pymysql

# 步骤
'''
1. 连接服务端
2. 用户认证
3. 发送指令
4. 提取结果
'''
# 1.连接服务器,获取连接对象(本质上就是封装好的socket)
conn = pymysql.connect(
    host = "127.0.0.1",  # 如果是本机,可以忽略
    port = 3306,         # 如果没有改过,可以忽略
    user = "root",
    password = "123",
    db = "test_7_17"
)
# 2.通过连接拿到游标对象
# 默认返回的游标是元祖类型,不方便使用,更换为字典类型的游标
c = conn.cursor(pymysql.cursors.DictCursor) 

# 3.执行sql
sql = "select * from user"

# 返回的是查询结果数量
count = c.execute(sql)

# 4.提取结果
print(c.fetchall()) # 查看所有

c.scroll(-2,mode="relative") # 因为查看完后,游标已经到最后面,所有要再次查看,就要移动游标,relative表示相对位置,即游标现在所在位置,-2表示,往前移动2个位置

print(c.fetchone()) # 查看一个值 默认是第一个,

c.scroll(0,mode="absolute") # absolute 表示绝对位置,即从第一个位置开始,0表示将游标移动到第一个位置

print(c.fetchmany(2)) # 查询多个括号内加参数,2表示查询2个值

# 5 关闭连接
c.close()
conn.close()

sql 注入攻击

​ 指的是一些程序员,在输入数据时,按照sql的语法规范,提交了用于攻击性目的的数据

如果避免这个问题?

​ 在服务端执行sql前 先做sql的验证

​ 在pymysql中,已经封装了验证操作,我们只需要将参数交给pymysql来做拼接即可.

import pymysql

conn = pymysql.connect(
    host = "127.0.0.1",
    port = 3306,
    user = "root",
    password = "123",
    db = "test_7_17"
    # autocommit = False  # 如果改成True 就表示开启自动提交,不常用,pymysql中默认开启事务,所以我们必须在每次执行完成后,commit提交下
)
c = conn.cursor(pymysql.cursors.DictCursor)

name = input("name>>>").strip()
pwd = input("pwd>>>").strip()
# 不能把变量名直接放到sql执行语句中,防止sql攻击
sql = "select * from user where name = %s and pwd = %s"

count = c.execute(sql,(name,pwd))

if count:
    print("登陆成功")
else:
    print("登陆失败")
print(c.fetchall())
c.scroll(-2,mode="relative")

print(c.fetchone())
c.scroll(0,mode="absolute")
print(c.fetchmany(2))

调用存储过程

# 创建存储过程
delimiter |
create procedure add1(in a int, in b int, out c int)
begin
set c = a + b;
end |
delimiter ;


# pymysql 中调用
import pymysql
conn = pymysql.connect(
    host = "127.0.0.1",
    port = 3306,
    user = "root",
    password = "123",
    db = "test_7_17")

c= conn.cursor(pymysql.cursors.DictCursor)
c.callproc("add1",(1,2,5)) # 1 对应 @_add1_0 ,2 对应 @_add1_1 , 5 对应 @_add1_2
c.execute("select @_add1_2") # 所以返回结果的调用得用第三个变量
print(c.fetchall())

# 调用存储过程时,传入参数,会自动定义成变量,
# 命名方式,@_过程的名称_参数的索引, 从0开始

猜你喜欢

转载自www.cnblogs.com/raynduan/p/11444780.html
今日推荐