继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【Python操作MySQL数据库】4-2 银行转账实例(源码)

泊之心
关注TA
已关注
手记 6
粉丝 9
获赞 117
# -*- coding: utf8 -*-  
import MySQLdb
import sys

reload(sys)
sys.setdefaultencoding('utf8')

class TransferMoney(object):
    def __init__(self,conn):
        self.conn = conn

    def tranfer(self,toAccount,fromAccount,money):
        self.check_acc_available(toAccount)
        self.check_acc_available(fromAccount)
        self.check_money_enough(fromAccount,money)
        self.reduce_money(fromAccount,money)
        self. add_money(toAccount,money)  
        print  u"转账成功"

    def  check_acc_available(self,account):
        try:
            cursor = self.conn.cursor()
            sql = "select * from user where name='%s'"%account
            cursor.execute(sql)
            if cursor.rowcount!=1:
                raise Exception("帐号%s不存在"%account)
        finally:
            cursor.close()

    def  check_money_enough(self,account,money):
        try:   
            cursor = self.conn.cursor()
            sql = "select money from user where name='%s'"%account
            cursor.execute(sql)      
            account_money = cursor.fetchone()[0]
            if account_money < money:
                raise Exception("账户%s:余额为%s,余额不足"%(account,account_money))
        finally:
            cursor.close()

    def  reduce_money(self,account,money):
        try:
            cursor = self.conn.cursor()
            sql = "update user set money=money-%s where name='%s'"%(money,account)
            cursor.execute(sql)
            if cursor.rowcount!=1:
                raise Exception("扣款失败")            
        finally:
            cursor.close()

    def  add_money(self,account,money):
        try:
            cursor = self.conn.cursor()
            sql = "update user set money=money+%s where name='%s'"%(money,account)
            cursor.execute(sql)
            if cursor.rowcount!=1:
                raise Exception("加款失败")               
        finally:
            cursor.close()

conn = MySQLdb.Connect(host="127.0.0.1",port=3306,user="root",passwd="123456",db="test",charset="utf8")
cursor = conn.cursor()
tr_money  = TransferMoney(conn)

try:    
    tr_money.tranfer("Tom","Jim",10)    
    conn.commit()
except Exception as e:  
    print u"转账出错:"+str(e)
    conn.rollback()
finally:
    conn.close()
打开App,阅读手记
3人推荐
发表评论
随时随地看视频慕课网APP