# -*- 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人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦