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学好

 

参考资料:

    http://www.imooc.com/

 

 

作者:陆炫志

出处:xuanzhi的博客 http://www.cnblogs.com/xuanzhi201111

您的支持是对博主最大的鼓励,感谢您的认真阅读。本文版权归作者所有,欢迎转载,但请保留该声明。

 

posted @ 2016-01-23 16:45  GoogSQL  阅读(1397)  评论(0编辑  收藏  举报