手记

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

# -*- 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人推荐
随时随地看视频
慕课网APP