为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
Python
# -*- 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()
点击查看更多内容
3人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消