Python实现完整的事务操作示例

时间:2021-10-09 01:07:31

本文实例讲述了Python事务操作实现方法。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#coding=utf-8
import sys
import MySQLdb
class TransferMoney(object):
  def __init__(self,conn):
    self.conn = conn
  #检查账户是否合法
  def check_acct_avaiable(self,acctid):
    cursor = self.conn.cursor()
    try:
      sql = "select * from account where acctid=%s" % acctid
      cursor.execute(sql)
      print "check account:" + sql
      rs = cursor.fetchall()
      if len(rs) != 1:
        raise Exception("account %s illega" % 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("account %s not enough money" % 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("reduce money fail %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("add money fail %s" % acctid)
    finally:
      cursor.close()
  #主执行语句
  def transfer(self,source_acctid,target_acctid,money):
    try:
      self.check_acct_avaiable(source_acctid)
      self.check_acct_avaiable(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 = MySQLdb.Connect(host = '127.0.0.1',port=3306,user='root',passwd='',db='test',charset='utf8')
  tr_money = TransferMoney(conn)
  try:
    tr_money.transfer(source_acctid,target_acctid,money)
  except Exception as e:
    print "Happen:" + str(e)
  finally:
    conn.close()

希望本文所述对大家Python程序设计有所帮助。