Simple transaction rollback of Pymsql

Original link: http://www.cnblogs.com/HapyyHao1314/p/7384436.html


#
coding:utf-8 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 test_rowback WHERE =%s" % acctid cursor.execute(sql) rs = cursor.fetchall () IF len (rs) = 1! : The raise Exception ( " Sorry,% s account does not exist, please check the information you entered is incorrect when " % acctid) a finally : cursor.close() def has_enough_money(self,acctid, money): cursor = self.conn.cursor() try: sql = "SELECT * FROM test_rowback WHERE id=%s and user_money>=%s" % (acctid,money) cursor.execute(sql) rs = cursor.fetchall () IF len (rs) = 1! : The raise Exception ( " due to lack of money leads to% s Account Transfer Failed " % acctid) a finally : cursor.close() def reduce_money(self,acctid, money): cursor = self.conn.cursor() try: sql = "UPDATE test_rowback SET user_money=user_money-%s WHERE id=%s" % (money,acctid) cursor.execute(sql) IF cursor.rowcount = 1! : The raise Exception ( " Account Transfer Failed% s " % acctid) the else : Print ( " transfer success " ) a finally : cursor.close() def add_money(self,acctid, money): cursor = self.conn.cursor() try: sql = 'UPDATE test_rowback SET user_money=user_money+%s WHERE id=%s' % (money, acctid) cursor.execute(sql) IF cursor.rowcount = 1! : The raise Exception ( " Accounts receivable failed% s " % acctid) the else : Print ( " receivables success " ) a 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 and if __name__=="__main__": give_accid=1 accept_accid=2 money=100 conn=pymysql.connect( host='127.0.0.1', port=3306, user='root', passwd='root', db='Python_test', charset='utf8' ) tr_money=TransferMoney(conn) try: tr_money.transfer(give_accid, accept_accid, money) except Exception as e: print(e) finally: conn.close()



Create a database statement

CREATE TABLE test_rowback(
    id INT,
    user_name VARCHAR(1000),
    user_passwd VARCHAR(1000),
    user_money INT    
)ENGINE =INNODB DEFAULT CHARSET = utf8;

Note: When you create a database, you must add this sentence ENGINE = INNODB DEFAULT CHARSET = utf8;

 

Reproduced in: https: //www.cnblogs.com/HapyyHao1314/p/7384436.html

Guess you like

Origin blog.csdn.net/weixin_30363509/article/details/94791923