有案例源码吗?
有案例源码吗?
有案例源码吗?
2018-05-21
# coding:utf-8 #import pymysql import pymysql import sys class TransferMoney(object): def __init__(self,db): self.db = db def transfer(self, source, target, money): try: self.checkid(source) self.checkid(target) self.check_money(source, money) self.reduce(source, money) self.add(target, money) self.db.commit() except Exception as e: self.db.rollback() raise e def checkid(self, source): try: cursor = self.db.cursor() sql = "select * from bank where id = %s" % source cursor.execute(sql) rs = cursor.fetchall() if len(rs) != 1: raise Exception("%s not exist" % source) finally: cursor.close() def check_money(self, source, money): try: cursor = self.db.cursor() sql = "select * from bank where id = %s and mondy > %s" % (source,money) cursor.execute(sql) rs = cursor.fetchall() if len(rs) != 1: raise Exception("%s not money" % source) finally: cursor.close() def reduce(self, source, money): try: cursor = self.db.cursor() sql = "update bank set mondy = mondy-%s where id = %s" %(money, source) cursor.execute(sql) rs = cursor.fetchall() if cursor.rowcount != 1: raise Exception("%s not money" % source) finally: cursor.close() def add(self, target, money): try: cursor = self.db.cursor() sql = "update bank set mondy = mondy+%s where id = %s" % (money, target) cursor.execute(sql) rs = cursor.fetchall() if cursor.rowcount != 1: raise Exception("%s not money" % target) finally: cursor.close() if __name__ == '__main__': source = 1 target = 2 money = 3000 db = pymysql.connect("localhost", "root", "toor", "spider", charset="utf8") try_money = TransferMoney(db) try: try_money.transfer(source,target,money) except Exception as e: print(e) finally: db.close() #coding:utf-8 # import MySQLdb # #建立和数据库的连接 # db = MySQLdb.connect(host= 'localhost',user="root",passwd="toor",db = "spider") # #获取操作游标 # cursor = db.cursor() # #执行sql # cursor.execute("SELECT VERSION()") # # # 使用 fetchone() 方法获取单条数据. # data = cursor.fetchone() # # print("Database version : %s " % data) # # # 关闭数据库连接 # db.close()
举报