由于 MySQLdb 模块还不支持 Python3.x,所以 Python3.x 如果想连接MySQL需要安装 pymysql 模块。
pymysql 模块可以通过 pip 安装。但如果你使用的是 pycharm IDE,则可以使用 project python 安装第三方模块。
[File] >> [settings] >> [Project: python] >> [Project Interpreter] >> [Install按钮]
由于Python统一了数据库连接的接口,所以 pymysql 和 MySQLdb 在使用方式上是类似的:
pymysql.Connect()参数说明
connection对象支持的方法
cursor对象支持的方法
==================MySQL===================
首先在连接数据库之前,先创建一个交易表,方便测试 pymysql 的功能:
DROP TABLE IF EXISTS `trade`;
CREATE TABLE `trade` (
`id` int(4) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(6) NOT NULL COMMENT '用户真实姓名',
`account` varchar(11) NOT NULL COMMENT '银行储蓄账号',
`saving` decimal(8,2) unsigned NOT NULL DEFAULT '0.00' COMMENT '账户储蓄金额',
`expend` decimal(8,2) unsigned NOT NULL DEFAULT '0.00' COMMENT '账户支出总计',
`income` decimal(8,2) unsigned NOT NULL DEFAULT '0.00' COMMENT '账户收入总计',
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `trade` VALUES (1,'乔布斯','18012345678',0.00,0.00,0.00);
==================Python===================
使用Python脚本实现增删改查和事务处理,源码如下:
import pymysql.cursors
# 连接数据库
connect = pymysql.Connect(
host='localhost',
port=3310,
user='woider',
passwd='3243',
db='python',
charset='utf8'
)
# 获取游标
cursor = connect.cursor()
# 插入数据
sql = "INSERT INTO trade (name, account, saving) VALUES ( '%s', '%s', %.2f )"
data = ('雷军', '13512345678', 10000)
cursor.execute(sql % data)
connect.commit()
print('成功插入', cursor.rowcount, '条数据')
# 修改数据
sql = "UPDATE trade SET saving = %.2f WHERE account = '%s' "
data = (8888, '13512345678')
cursor.execute(sql % data)
connect.commit()
print('成功修改', cursor.rowcount, '条数据')
# 查询数据
sql = "SELECT name,saving FROM trade WHERE account = '%s' "
data = ('13512345678',)
cursor.execute(sql % data)
for row in cursor.fetchall():
print("Name:%s\tSaving:%.2f" % row)
print('共查找出', cursor.rowcount, '条数据')
# 删除数据
sql = "DELETE FROM trade WHERE account = '%s' LIMIT %d"
data = ('13512345678', 1)
cursor.execute(sql % data)
connect.commit()
print('成功删除', cursor.rowcount, '条数据')
# 事务处理
sql_1 = "UPDATE trade SET saving = saving + 1000 WHERE account = '18012345678' "
sql_2 = "UPDATE trade SET expend = expend + 1000 WHERE account = '18012345678' "
sql_3 = "UPDATE trade SET income = income + 2000 WHERE account = '18012345678' "
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()
==================测试结果===================
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8