Pymysql 连接数据库增删改查操作与批处理

x33g5p2x  于2021-09-19 转载在 Mysql  
字(2.1k)|赞(0)|评价(0)|浏览(450)

首先还是第三方库的安装:

pymysql ----> 纯Python编写,安装一定会成功

mysqlclient ----> 底层用C编写,安装不一定会成功

import pymysql
第一步:创建连接
connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123456',database='hrs', charset='utf8mb4')
第二步:获取游标对象
cursor = connection.cursor()
第三步:通过游标对象像数据库发出SQL并获得执行结果
affected_rows = cursor.execute(
'sql语句'
 )
第四步:手动提交(操作成功)
connection.commit()

也可以在创建连接时在connect中设置autocommit=True参数为自动提交(不建议)。

第四步:手动回滚,若提交失败则撤销刚才的所有命令(操作失败)
connection.rollback()
第五步:关闭连接释放资源
connection.close()

增删改查基本都是以上5个步骤。

注意:在python中编写SQL语句时,绝不能使用字符串拼接以及格式化语句;例:f’'语句否则有折射攻击的风险有变量时用%s占位符(不是字符串占位符而是安全(security)占位符)

默认情况下创建连接,相当于开启了一个事务环境

事务:把若干个(增删改)操作视为一个不可分割的原子性操作要么全成功要么全失败

若操作成功,我们可以通过连接对象的commit方法手动提交

若操作失败,我们可以通过连接对象的rollback方法实现事务回滚

以删除为例的完整代码段:

try:
    # 第二步:创建游标对象
    cursor2 = connection.cursor()
    # 第三步:通过游标对象像数据库发出SQL并获得执行结果
    affected_rows = cursor2.execute(
        'delete from tb_dept where dno = 60'
    )
    if affected_rows == 1:
        print('数据删除成功!')
    # 第四步:手动提交
    connection.commit()

except pymysql.MySQLError:
    # 第四步:手动回滚,若提交失败则撤销刚才的所有命令
    connection.rollback()
    print('数据删除失败,已撤销删除操作!')
finally:
    # 第五步:关闭连接释放资源
    connection.close()

查询

查询与其他(增删改)有点小区别单独分享一下。

首先设置游标对象为字典型:pymysql.cursors.DictCursor也可以在创建连接时在connect中设置

with connection.cursor(pymysql.cursors.DictCursor) as cursor:
    affected_rows = cursor.execute(
        'select dno as 部门编号,dname as 部门名称,dloc as 部门所在地 from tb_dept'
    )

抓取查询到的结果,返回的是一个同迭代器的容器fetchone一次拿一个(拿一个少一个)

dept_row = cursor.fetchone()

打印抓取到的内容

while dept_row:
        # print(f'部门编号:{dept_row[0]}  部门名称:{dept_row[1]}  部门所在地:{dept_row[2]}')
        print(dept_row)
        dept_row = cursor.fetchone()
将查询封装为类
import pymysql

class Dept:
    def __init__(self,no,name,location):
        self.no = no
        self.name = name
        self.location = location
    def __str__(self):
        return f'编号:{self.no}\n部门名称:{self.name}\n部门所在地:{self.location}\n'

其他步骤完全相同除打印时的一点差距

dept_row = cursor.fetchone()
while dept_row:
# 通过获取到的部门数据创建一个部门对象
   dept = Dept(**dept_row)
   print(dept.no,dept.name,dept.location,sep='\t')
   dept_row = cursor.fetchone()

批处理

批处理可大幅减少处理数据时间

time_before = time.time()
with connection.cursor() as cursor:
    for i in range(50001):
        cursor.execute(
        'insert into tb_user (user_name) values(%s)',
            (f'user{i}')
        )
    connection.commit()
time_after = time.time()
print(f'运行时间:{time_after - time_before}')

通过循环添加50000条数据,运行时间为

批处理:

添加结果:

数据更大或者机器性能稍弱效果可能更加明显

相关文章