pymysql安装_pymysql

a8370a4f5979a78726df541de1418cad.png
安装: pip3 install pymysql

1. 查询操作

操作步骤:

  1. 导包
  2. 创建连接对象
  3. 创建游标对象
  4. 执行 SQL 语句
  5. 关闭游标对象
  6. 关闭连接对象
# 1. 导包
import pymysql
# 2. 创建连接对象
conn = pymysql.connect(host='localhost', port=3306,
                       user='***', password='***',
                       database='***', charset='utf8')
# 3. 创建游标对象 连接对象.cursor()
cursor = conn.cursor()
# 4. 执行 SQL 语句
# 4.1 组织 SQL 语句
sql = "select * from stu;"
# 4.2 执行 SQL 语句, 游标对象.execute(sql)
# 返回值: 是影响的条数(即查询的条数), 查询结果保存在游标对象中
count = cursor.execute(sql)
print(f'查询结果的条数有{count} 条')
# 获取查询结果, 游标对象.fetchone()   # 元组,获取一条数据
print(cursor.fetchone())
print('-' * 20)
# 获取查询结果, 游标对象.fetchall()   # 元组,获取所有的数据
# print(cursor.fetchall())
for row in cursor.fetchall():
    print(row)
# 5. 关闭游标对象
cursor.close()
# 6. 关闭连接对象
conn.close()

2. 增删改操作

增删改操作会修改表数据, 涉及到事务, pymysql 默认是开启事务的, 必须手动提交或者回滚事务

操作步骤:

  1. 导包
  2. 创建连接对象
  3. 创建游标对象
  4. 执行 SQL 语句
  5. 事务的处理
  6. 关闭游标对象
  7. 关闭连接对象
# 1. 导包
import pymysql
# 2. 创建连接对象
conn = pymysql.connect(host='localhost', port=3306, 
                       user='***', password='***',
                       database='***', charset='utf8')
# 3. 创建游标对象
cursor = conn.cursor()
# 4. 执行 SQL 语句
# 4.1 组织 SQL 语句
sql = 'update stu set  age = 18 where id = 17;'
# 4.2 执行 SQL 语句
try:
    cursor.execute(sql)  # 可能存在多条 SQL 语句, 一半执行成功了, 执行剩下的报错
    # 如果没有报错.提交事务  连接对象.commit()
    conn.commit()
except Exception as e:
    # 5. 事务的处理
    print(e)
    conn.rollback()
# 6. 关闭游标对象
cursor.close()
# 7. 关闭连接对象
conn.close()

3. sql 注入问题以及解决

避免使用字符串的格式化, 使用 SQL 参数化(传参)
# 1. 导包
import pymysql
# 2. 创建连接对象
conn = pymysql.connect(host='localhost', port=3306, 
                       user='***', password='***',
                       database='***', charset='utf8')
# 3. 创建游标对象 连接对象.cursor()
cursor = conn.cursor()
# 4. 执行 SQL 语句
name = input('请输入要查询的学生的名字:')
sql = "select * from stu where name = %s;"
# SQL 注入问题: 用户提交恶意的数据,  ' or 1 = 1 or '
# sql select * from stu where name = '' or 1 = 1 or '';
# count = cursor.execute(sql, [name])
count = cursor.execute(sql, (name,))
print(f'查询结果的条数有{count} 条')
for row in cursor.fetchall():
    print(row)
# 5. 关闭游标对象
cursor.close()
# 6. 关闭连接对象
conn.close()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值