Python3 connects to MySQL (pymysql) to simulate the transfer implementation code, python3pymysql
The examples in this article share with you the specific implementation code of Python3 connecting to MySQL for your reference. The specific content is as follows:
# Coding: utf8import sysimport 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.exe cute (SQL) print ("check_acct_available:" + SQL) rs = cursor. fetchall () if len (rs )! = 1: raise Exception ("account % s does not exist" % 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.exe cute (SQL) print ("has_enough_money: "+ SQL) rs = cursor. fetchall () if len (rs )! = 1: raise Exception ("account % s balance is insufficient" % acctid) finally: cursor. close () def performance_money (self, acctid, money): cursor = self. conn. cursor () try: SQL = "update account set money = money-% s where acctid = % s" % (money, acctid) cursor.exe cute (SQL) print ("performance_money: "+ SQL) if cursor. rowcount! = 1: raise Exception ("account % s payment deduction failed" % 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.exe cute (SQL) print ("add_money: "+ SQL) if cursor. rowcount! = 1: raise Exception ("account % s failed to add" % 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. performance_money (source_acctid, money) self. add_money (target_acctid, money) self. conn. commit () commit t 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) failed t Exception as e: print ("problem" + str (e) finally: conn. close ()
The above is all the content of this article. I hope it will help you learn python programming.