pymysql

-- 授权加创建mysql账号一步到位,%代表远程
grant all on *.* to 'gudon'@'%' identified by '123';
mysql> flush privileges;  -- 使操作结果立即生效
-- 建表
mysql> select * from userinfo;
+----+--------+-------+
| id | user   | pwd   |
+----+--------+-------+
|  1 | gudon  | 123   |
|  2 | Astro  | 1234  |
|  3 | Nurato | 12345 |
+----+--------+-------+


# pip3 install pymysql
import pymysql

user = input('user>>').strip()
pwd = input('pwd>>').strip()


# 建连接
conn = pymysql.connect(
    host='127.0.0.1',
    port=3306,
    user='gudon',
    password='123',
    db='db9',
    charset='utf8'
)

# 拿到游标
cursor = conn.cursor()

# 执行sql
sql = 'select * from userinfo where user = "%s" and pwd = "%s"' %(user, pwd)

rows = cursor.execute(sql)

cursor.close()
conn.close()

# 进行判断
if rows:
    print('登录成功')
else:
    print('登录失败')
    
-------------------结果----------------------
user>>gudon
pwd>>123
登录成功

sql注入:

user>>gudon "-- xxxx
pwd>>
登录成功

-- 此时sql 为 
select * from userinfo where user = "gudon "-- xxxx" and pwd = ""
后面的条件被注释掉了


user>>xxx" or 1=1 -- xxx
pwd>>
登录成功
实际执行的sql为 select * from userinfo where user = "xxx" or 1=1 -- xxx" and pwd = ""

sql注入解决办法:

# 执行sql
sql = 'select * from userinfo where user=%s and pwd=%s'
rows = cursor.execute(sql, (user, pwd))

2 增删改查

(1)增删改

import pymysql

# 建连接
conn = pymysql.connect(
    host='127.0.0.1',
    port=3306,
    user='gudon',
    password='123',
    db='db9',
    charset='utf8'
)
# 拿游标
cursor = conn.cursor()
# 执行sql
# 增、删、改
sql = 'insert into userinfo(user,pwd) values (%s,%s)'

# 插入单条数据
# rows = cursor.execute(sql,('jack','123'))
# print(rows)

# 插入多条数据
rows = cursor.executemany(sql,[('gd01','123'),('gd02','123'),('zs','123')])
print(rows)
conn.commit()  # commit 后才会真正更改数据库中的数据

# 关闭
cursor.close()
conn.close()

(2) 查

import pymysql

# 建连接
conn = pymysql.connect(
    host='127.0.0.1',
    port=3306,
    user='gudon',
    password='123',
    db='db9',
    charset='utf8'
)
# 拿游标
# cursor = conn.cursor()
cursor = conn.cursor(pymysql.cursors.DictCursor) # 使查询结果为字典格式

# 执行sql
# 查
sql = 'select * from userinfo'

# 插入单条数据
rows = cursor.execute(sql)  # 返回查询条数

# print(cursor.fetchone())  # (1, 'gudon', '123')
# print(cursor.fetchone())  # (2, 'Astro', '1234')
# 取到最后一个没有数据了,则返回None

print(cursor.fetchmany(2))  # 指定取出条数
# [{'id': 1, 'user': 'gudon', 'pwd': '123'}, {'id': 2, 'user': 'Astro', 'pwd': '1234'}]

# print(cursor.fetchall())  # 取出所有


# cursor.scroll(3,mode='absolute') # 相对绝对位置移动,从0开始数3个,下次取第4条
# cursor.scroll(3,mode='relative') # 相对当前位置移动 ,相对于游标目前的位置,往后数3个


# 关闭
cursor.close()
conn.close()

原文地址:https://www.cnblogs.com/friday69/p/9752092.html