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的时候,是通过”游标”来进行操作的. ...
随机推荐
- 关于java11 - 应该知道的
Local Variable Type Inference# HTTP Client# Collections# Streams# Optionals# Strings# InputStreams# ...
- mysql 开源 ~ canal+otter系列(1)
一 简介: 今天咱们来聊聊 canal和otter的组合搭配吧二 概念统计 1. 基于Canal开源产品,获取数据库增量日志数据. 2. 典型管理系统架构,manager(web管理)+nod ...
- 新eclipse 打开就版本的工作空间提示:
点击OK后,完美呈现 (因为本人的旧版本已经被我玩坏了,有些菜单已经打不开)
- 关于vue监听dom与传值问题
1. 代码初始化一次执行部分属性为空的情况 原因: 异步加载 + 立马 传值时 直接渲染 dom里面 能实时更新 (无影响) 不能直接dom中渲染(有影响) 解决方法:需要通过监听的方式来处 ...
- Light oj 1099 - Not the Best 次短路
题目大意:求次短路. 题目思路:由于可能存在重边的情况所以不能采用邻接矩阵储存图,我用了邻接表来存图. 由起点S到终点E的次短路可能由以下情况组成: 1.S到v点的次短路 + v到E的距离 2.S到v ...
- linux中创建python的虚拟环境
1,何为虚拟环境 linux是支持多用户的系统,如果某一位用户不想使用公用环境,想指定特殊的python版本安装仅供个人使用的一些包,那么虚拟环境将满足他的要求 2,虚拟环境使用需要virtualen ...
- Deep Learning(花书)教材笔记-Math and Machine Learning Basics(线性代数拾遗)
I. Linear Algebra 1. 基础概念回顾 scalar: 标量 vector: 矢量,an array of numbers. matrix: 矩阵, 2-D array of numb ...
- Nginx 开启目录下载
平时应用中,我们大都用apache搭建下载页面.毕竟Apache搭建起来非常方便,yum安装,创建目录就可以了. 但有时还是需要用nginx配置下载页面.这里就是一个简单的配置nginx下载页面的过程 ...
- python3+selenium框架设计07-unittest单元测试框架
可以自行百度学习下单元测试框架,或者看Python3学习笔记26-unittest模块 在项目下新建一个entrance.py文件.并使用之前的测试用例进行演示.目前项目结构. 在entrance ...
- python3+selenium入门12-警告框处理
在WebDriver中要处理JS生成的alert.confirm以及prompt,需要使用到switch_to_alert()定位到alert/confirm/prompt,然后再使用text.acc ...