栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

4-2 银行转账实例(源码)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/225884.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号