为了账号安全,请及时绑定邮箱和手机立即绑定

正在回答

2 回答

nice

0 回复 有任何疑惑可以回复我~
# 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()


0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
Python操作MySQL数据库
  • 参与学习       85036    人
  • 解答问题       171    个

本视频教程讲解Python如何开发MySQL数据库程序

进入课程

有案例源码吗?

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信