Python3连接MySQL(pymysql)模拟转账实现代码
作者:沙拉虎 时间:2024-01-21 09:37:45
本文实例为大家分享了Python3连接MySQL模拟转账的具体实现代码,供大家参考,具体内容如下
# coding:utf8
import sys
import pymysql
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 where acctid=%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 where acctid=%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 set money=money-%s where acctid=%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 set money=money+%s where acctid=%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
if __name__ == "__main__":
source_acctid = sys.argv[1]
target_acctid = sys.argv[2]
money = sys.argv[3]
conn = pymysql.Connect(
host = 'localhost',
unix_socket = "..mysql/mysql.sock",
port = 3306,
user = 'root',
passwd = '',
db = 'python_db',
)
tr_money = TransferMoney(conn)
try:
tr_money.transfer(source_acctid,target_acctid,money)
except Exception as e:
print ("出现问题" + str(e))
finally:
conn.close()
标签:Python3,MySQL,pymysql,转账
0
投稿
猜你喜欢
浅析Python 序列化与反序列化
2023-05-01 14:36:16
浅谈python新式类和旧式类区别
2023-03-16 16:47:37
oracle数据库冷备份的方法
2023-07-19 09:51:19
scrapy+flask+html打造搜索引擎的示例代码
2022-06-04 01:15:33
新手学python应该下哪个版本
2021-09-06 00:04:45
mysql二进制日志文件恢复数据库
2024-01-16 10:55:05
MySQL8.0.23安装超详细教程
2024-01-26 05:06:18
centos源码编译php5 mcrypt模块步骤详解
2024-05-08 10:15:34
在Python的web框架中编写创建日志的程序的教程
2021-11-25 05:14:07
IE及Opera浏览器兼容笔记
2008-08-21 17:53:00
mysql查询时offset过大影响性能的原因和优化详解
2024-01-13 14:17:36
Git基本概述
2023-12-07 14:13:28
使用memory_profiler监测python代码运行时内存消耗方法
2022-03-02 06:49:56
BERT vs GPT自然语言处理中的关键差异详解
2022-04-01 08:15:36
SpringBoot+Mybatis-Plus实现mysql读写分离方案的示例代码
2024-01-17 02:13:32
Go语言通过WaitGroup实现控制并发的示例详解
2023-06-29 01:04:27
pandas 使用apply同时处理两列数据的方法
2021-09-27 07:35:30
MySQL中replace into语句的用法详解
2024-01-20 10:45:53
Python深入浅出分析enum枚举类
2022-07-07 15:09:14
CI框架整合smarty步骤详解
2023-11-14 11:18:11