Python3連接MySQL(pymysql)模擬轉(zhuǎn)賬實現(xiàn)代碼
更新時間:2016年05月24日 16:11:32 作者:沙拉虎
這篇文章主要介紹了Python3連接MySQL(pymysql)模擬轉(zhuǎn)賬實現(xiàn)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了Python3連接MySQL模擬轉(zhuǎn)賬的具體實現(xiàn)代碼,供大家參考,具體內(nèi)容如下
# 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 ("出現(xiàn)問題" + str(e)) finally: conn.close()
以上就是本文的全部內(nèi)容,希望對大家學(xué)習(xí)python程序設(shè)計有所幫助。
您可能感興趣的文章:
- Python中操作mysql的pymysql模塊詳解
- Python MySQL數(shù)據(jù)庫連接池組件pymysqlpool詳解
- Python中模塊pymysql查詢結(jié)果后如何獲取字段列表
- python使用pymysql實現(xiàn)操作mysql
- 詳解使用pymysql在python中對mysql的增刪改查操作(綜合)
- Python 3.x 連接數(shù)據(jù)庫示例(pymysql 方式)
- Python使用pymysql從MySQL數(shù)據(jù)庫中讀出數(shù)據(jù)的方法
- python 3.6 +pyMysql 操作mysql數(shù)據(jù)庫(實例講解)
- Python使用pymysql小技巧
- python3.6使用pymysql連接Mysql數(shù)據(jù)庫
- python和mysql交互操作實例詳解【基于pymysql庫】
相關(guān)文章
Python中字符串,列表與字典的常用拼接方法總結(jié)
有時在數(shù)據(jù)處理時,需要對數(shù)據(jù)進行拼接處理,比如字符串的拼接、列表的拼接等,本文主要是介紹了字符串、列表、字典常用的拼接方法,希望對大家有所幫助2024-02-02對Python2與Python3中__bool__方法的差異詳解
今天小編就為大家分享一篇對Python2與Python3中__bool__方法的差異詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11