Python操作MySQL案例
最近都在学习Python代码,希望学会Python后,能给我带来更高的工作效率,所以每天坚持学习和拷代码,下面是一个Python操作MySQL的一个实例,该实例可以让更多的人更好了解MySQLdb模块的使用。我是Python菜鸟,通过学习别人的实例来让自己学到更多Python知识。
案例:用Python实现银行转账
一、在MySQL创建一张表account表,然后在里面插入两条数据:
mysql> show create table account\G
*************************** 1. row ***************************
Table: account
Create Table: CREATE TABLE `account` (
`userid` int(11) DEFAULT NULL COMMENT '账号ID',
`money` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
1 row in set (0.02 sec) mysql>
当前数据:
mysql> select * from account;
+--------+-------+
| userid | money |
+--------+-------+
| 1 | 200 |
| 2 | 200 |
+--------+-------+
2 rows in set (0.00 sec) mysql>
编辑脚本money.py文件,运行些脚本需要安装MySQLdb模块,详细安装和基本的使用可以参考我的博客:http://www.cnblogs.com/xuanzhi201111/p/5144982.html
#!/usr/bin/env python
#coding:utf-8
#name:money.py import sys
import MySQLdb class TransferMoney(object):
def __init__(self,conn):
self.conn = conn #用于检查是否存在转账用户或者被转账用户
def check_user_exist(self, userid):
cursor = self.conn.cursor()
try:
sql = "select * from account where userid = %s" % userid
cursor.execute(sql)
print "\033[;32m验证用户是否存在: \033[0m" + sql
except Exception,e:
raise Exception('执行sql错误:%s' % e)
else:
rs = cursor.fetchall()
if len(rs) != 1:
raise Exception ("账号%s不存在" % userid)
finally:
cursor.close() #用于检查是用户是否有足够的钱转给别人
def has_enough_money(self,source_userid,money):
cursor = self.conn.cursor()
try:
sql = "select * from account where userid = %s and money > %s" % (source_userid,money)
cursor.execute(sql)
print "\033[;32m检查是否有足够的钱: \033[0m" + sql
except Exception,e:
raise Exception('执行sql错误:%s' % e)
else:
rs = cursor.fetchall()
if len(rs) != 1:
raise Exception ("账号%s余额不足" % source_userid)
finally:
cursor.close() #用于减去转掉的部份金额
def reduce_money(self,source_userid,money):
cursor = self.conn.cursor()
try:
sql = "update account set money = money - %s where userid=%s" % (money,source_userid)
cursor.execute(sql)
print "\033[;32m从源账户%s里扣掉对应的金额: \033[0m" % (source_userid) + sql
except Exception,e:
raise Exception('执行sql错误:%s' % e)
else:
rs = cursor.rowcount
if rs!=1:
raise Exception("账号%s减款失败" % source_userid)
finally:
cursor.close() #用于把别人转过来的钱加到目标用户的金额上
def add_money(self,target_userid,money):
cursor=self.conn.cursor()
try:
sql="update account set money = money + %s where userid=%s" % (money,target_userid)
cursor.execute(sql)
print '\033[;32m目标账户%s加上转过来的金额:\033[0m' % (target_userid) + sql
except Exception,e:
raise Exception('执行sql错误:%s' % e)
else:
rs=cursor.rowcount
if rs!=1:
raise Exception("账号%s加钱失败" % target_userid)
finally:
cursor.close() #用于转账后的查询账号的金额
def check_money(self,source_userid):
cursor=self.conn.cursor()
try:
sql="select * from account where userid=%s" % (source_userid)
cursor.execute(sql)
except Exception,e:
raise Exception('执行sql错误:%s' % e)
else:
rs = cursor.fetchall()
for row in rs:
print "userid=%d, 现在的金额=%d" % row
finally:
cursor.close() #主函数,调用以上的函数形成一个事务
def transfer(self, source_userid, target_userid, money):
try:
self.check_user_exist(source_userid)
self.check_user_exist(target_userid)
self.has_enough_money(source_userid,money)
self.reduce_money(source_userid,money)
self.add_money(target_userid,money)
self.conn.commit()
self.check_money(source_userid)
self.check_money(target_userid)
except Exception as e:
self.conn.rollback()
raise e if __name__ == '__main__':
source_userid = sys.argv[1]
target_userid = sys.argv[2]
money = sys.argv[3] conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='123456',port=3306,db='python')
tr_money = TransferMoney(conn) try:
tr_money.transfer(source_userid,target_userid,money)
except Exception as e:
print "\033[;31m出现问题:\033[0m" + str(e)
finally:
conn.close()
代码验证:
从账号1 转账100块给账号 2:
[root@Python test]# python money.py 1 2 100
验证用户是否存在: select * from account where userid = 1
验证用户是否存在: select * from account where userid = 2
检查是否有足够的钱: select * from account where userid = 1 and money > 100
从源账户1里扣掉对应的金额: update account set money = money - 100 where userid=1
目标账户2加上转过来的金额:update account set money = money + 100 where userid=2
userid=1, 现在的金额=100
userid=2, 现在的金额=300
从账号 1 转500给账号 2,会出现余额不足
[root@Python test]# python money.py 1 2 500
验证用户是否存在: select * from account where userid = 1
验证用户是否存在: select * from account where userid = 2
检查是否有足够的钱: select * from account where userid = 1 and money > 500
出现问题:账号1余额不足
从账号 2 转账200块给账号 1
[root@Python test]# python money.py 2 1 200
验证用户是否存在: select * from account where userid = 2
验证用户是否存在: select * from account where userid = 1
检查是否有足够的钱: select * from account where userid = 2 and money > 200
从源账户2里扣掉对应的金额: update account set money = money - 200 where userid=2
目标账户1加上转过来的金额:update account set money = money + 200 where userid=1
userid=2, 现在的金额=100
userid=1, 现在的金额=300
可以看到正常的转账了,初学Python,还有很多需要优化的地方,希望大家指出我的不足,让我更好更快的成长,同时也希望大家一起把Python学好
参考资料:
|
作者:陆炫志 出处:xuanzhi的博客 http://www.cnblogs.com/xuanzhi201111 您的支持是对博主最大的鼓励,感谢您的认真阅读。本文版权归作者所有,欢迎转载,但请保留该声明。 |
Python操作MySQL案例的更多相关文章
- python操作mysql——mysql.connector
连接mysql, 需要mysql connector, conntector是一种驱动程序,python连接mysql的驱动程序,mysql官方给出的名称为connector/python, 可参考m ...
- 数据备份 及 Python 操作 Mysql
一 MySQL数据备份 #1. 物理备份: 直接复制数据库文件,适用于大型数据库环境.但不能恢复到异构系统中如Windows. #2. 逻辑备份: 备份的是建表.建库.插入等操作所执行SQL语句,适用 ...
- python操作MySQL、事务、SQL注入问题
python操作MySQL python中支持操作MySQl的模块很多 其中最常见就是'pymysql' # 属于第三方模块 pip3 install pymysql # 基本使用 import py ...
- python操作MySQL,SQL注入的问题,SQL语句补充,视图触发器存储过程,事务,流程控制,函数
python操作MySQL 使用过程: 引用API模块 获取与数据库的连接 执行sql语句与存储过程 关闭数据库连接 由于能操作MySQL的模块是第三方模块,我们需要pip安装. pip3 insta ...
- python操作MySQL与MySQL补充
目录 python操作MySQL 基本使用 SQL注入问题 二次确认 视图 触发器 事务 存储过程 函数 流程控制 索引 练习 python操作MySQL python中支持操作MySQL的模块很多, ...
- Python(九) Python 操作 MySQL 之 pysql 与 SQLAchemy
本文针对 Python 操作 MySQL 主要使用的两种方式讲解: 原生模块 pymsql ORM框架 SQLAchemy 本章内容: pymsql 执行 sql 增\删\改\查 语句 pymsql ...
- 练习:python 操作Mysql 实现登录验证 用户权限管理
python 操作Mysql 实现登录验证 用户权限管理
- Python操作MySQL
本篇对于Python操作MySQL主要使用两种方式: 原生模块 pymsql ORM框架 SQLAchemy pymsql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb ...
- Python操作Mysql之基本操作
pymysql python操作mysql依赖pymysql这个模块 下载安装 pip3 install pymysql 操作mysql python操作mysql的时候,是通过”游标”来进行操作的. ...
随机推荐
- MySQL报错解决方案:2013-Lost connection
今天上课的时候,在搭建完MySQL测试环境中出现的问题,整理如下: 问题描述:搭建完MySQL,用远程连接工具(Navicat)连接时报错: 2013-Lost connection to MySQL ...
- C# 事务 四种事务隔离级别
http://www.zsythink.net/archives/1233 不同隔离级别的问题 脏读(Dirty Read) 一个事务处理过程里读取了另一个未提交的事务中的数据 例子: 当一个事务 ...
- 使用vmstat和iostat命令进行Linux性能监控【转】
转自:https://linux.cn/article-4024-1.html 这是我们正在进行的Linux命令和性能监控系列的一部分.vmstat和iostat两个命令都适用于所有主要的类unix系 ...
- ES6学习笔记六(Iterator和for..of)
{ let arr=['hello','world']; let map=arr[Symbol.iterator](); //返回false时继续执行,true停止执行! console.log(ma ...
- 【转】C++ 11 并发指南一(C++ 11 多线程初探)
引言 C++ 11自2011年发布以来已经快两年了,之前一直没怎么关注,直到最近几个月才看了一些C++ 11的新特性,算是记录一下自己学到的东西吧,和大家共勉. 相信Linux程序员都用过Pthrea ...
- oracle procedure存储过程
1.基本结构 CREATE OR REPLACE PROCEDURE 存储过程名字 ( 参数1 IN NUMBER, 参数2 IN NUMBER ) IS/AS 变量1 ; 变量2 DATE: BEG ...
- This Product is covered by one or more of the following......的问题
DELL台式机安装ubuntu后无法正常启动,黑屏显示:This Product is covered by one or more of the following...... 解决方案:进入BIO ...
- 微信小程序-动态设置背景色navigationBarBackgroundColor的值
查看API: wx.setNavigationBarColor(OBJECT) 代码: wx.setNavigationBarColor({ frontColor: '#ffffff', // 必写项 ...
- $Django 多对多-自定义第三张表 基于双下划线的跨表查询(补充)
自定义第三张表的好处:可以定义多个字段, 缺点:查询不方便(有方法解决) 1.第三张表设置外键,联合唯一(查询不方便) class Books(models.Model): name=models.C ...
- 解决mysql 主从数据库同步不一致的方法
接着上文 配置完Mysql 主从之后,在使用中可能会出现主从同步失败的情况. mysql> show slave status\G Slave_IO_Running: Yes Slave_SQL ...