python 简单的数据库操作之转账

介绍:本文是关于数据库的简单操作,实现转账(只是修改数据库中用户的账户金额)的功能

模块介绍:首先是入口主函数 主函数中实现转账方法  以及异常的处理:

  

if __name__ == "__main__":
    source_acctid = sys.argv[1] #获取命令行第一个参数
    target_acctid = sys.argv[2]
    money = sys.argv[3]
    
    #连接数据库
    conn = MySQLdb.Connect(host = '127.0.0.1',user = 'root',passwd = 'root',port = 3306,db = 'account')
    tr_money = TransferMoney(conn)
    
    try:
        tr_money.transfer(source_acctid,target_acctid,money)  #转账操作
    except Exception as e:
        print "出现问题" + str(e)
    finally:
        conn.close()#关闭数据库连接
 

然后是实现转账的类,以及类中实现的方法 1.判断用户账户中的金额 2.判断账户是否存在 3.扣除账户金额  4.增加账户金额

class TransferMoney(object):
    
    def __init__(self, conn):
        self.conn = conn
        
    
    def check_acct_available(self, acctid):
        cursor = self.conn.cursor()
        try:
            sql = "select * from account_user where accountid=%s"%acctid
            cursor.execute(sql)
            print "check_acct_available:"+sql
            rs = cursor.fetchall() 
            if len(rs)!=1:
                raise Exception("账号%s不存在"%acctid)
        finally:
            cursor.close()
    
    
    
    
    def has_enough_money(self, acctid, money):
        cursor = self.conn.cursor()
        try:
            sql = "select * from account_user where accountid=%s and money>%s"% (acctid,money)
            cursor.execute(sql)
            print "has_enough_money:"+sql
            rs = cursor.fetchall()
            if len(rs)!=1:
                raise Exception("账号%s没有足够的钱"%acctid)
        finally:
            cursor.close()
    
    
    def reduce_money(self, acctid, money):
        cursor = self.conn.cursor()
        try:
            sql = "update account_user set money=money-%s where accountid=%s"% (money,acctid)
            cursor.execute(sql)
            print "reduce_money:"+sql
            if cursor.rowcount!=1:
                raise Exception("账号%s减款失败"%acctid)
        finally:
            cursor.close()
    
    
    def add_money(self, acctid, money):
        cursor = self.conn.cursor()
        try:
            sql = "update account_user set money=money+%s where accountid=%s"% (money,acctid)
            cursor.execute(sql)
            print "add_money:"+sql
            if cursor.rowcount!=1:
                raise Exception("账号%s加款失败"%acctid)
        finally:
            cursor.close()
    
    
    def transfer(self,source_acctid,target_acctid,money):
        try:
            self.check_acct_available(source_acctid) #检查转账账户是否可用
            self.check_acct_available(target_acctid)
            self.has_enough_money(source_acctid,money) #检查账户钱是否足够
            self.reduce_money(source_acctid,money)  #扣除钱
            self.add_money(target_acctid,money) #转账加钱
            self.conn.commit() 
        except Exception as e:
            self.conn.rollback()  #如果有步骤出错 则事务回滚
            raise e     # raise的作用是将异常抛出到上一级处理


posted @ 2017-08-03 22:15  非我非非我  阅读(372)  评论(0编辑  收藏  举报