pymysql用法 - python连接mysql
# python包选择:pymysql
python3中有几个支持mysql的包,最常用的是pymysql
MySQLdb: 只支持python2,不支持python3
PyMSQL: PyMSQL好部署,但是很慢,生产环境还是推荐mysqlclient(也就是Python3版本的MySQLdb)。PyMYSQL可以配合PyPy使用试试。
mysqlclient : 这个其实最好,centos安装的时候需要先安装mysql-devel。通过mysql官方下载rpm包的方式安装了mysql和mysql-devel,然后再
pip install pymysql, pip install mysqlclient
直接用yum安装,会安装mariadb。下次试试mariadb能不能用。
https://www.zhihu.com/question/268449231/answer/337493223
# 事务
https://blog.csdn.net/mengyangcust/article/details/84752342
# -*- coding: utf-8 -*-
import pymysql.cursors
# 连接数据库
connect = pymysql.Connect(
host='localhost',
port=3310,
user='user',
passwd='123',
db='test',
charset='utf8'
)
# 事务处理
sql_1 = "UPDATE staff SET saving = saving + 1000 WHERE user_id = '1001' "
sql_2 = "UPDATE staff SET expend = expend + 1000 WHERE user_id = '1001' "
sql_3 = "UPDATE staff SET income = income + 2000 WHERE user_id = '1001' "
try:
cursor.execute(sql_1) # 储蓄增加1000
cursor.execute(sql_2) # 支出增加1000
cursor.execute(sql_3) # 收入增加2000
except Exception as e:
connect.rollback() # 事务回滚
print('事务处理失败', e)
else:
connect.commit() # 事务提交
print('事务处理成功', cursor.rowcount)
# 关闭连接
cursor.close()
connect.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
编辑 (opens new window)
上次更新: 2021/10/11, 12:43:58