#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pymssql
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import urllib2
class TransferMoney(object):
def __init__(self,conn):
self.conn=conn
def check_acct_available(self,acctid):
cursor=self.conn.cursor()
try:
sql='select * from hh where acctid=%s'%acctid
cursor.execute(sql)
print 'check_acct_available:'+sql
rs=cursor.fetchall()
print rs
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 hh where acctid=%s and money>%s'%(acctid,money)
cursor.execute(sql)
print 'has_enough_money:'+sql
rs=cursor.fetchall()
if len(rs)!=1:
print '账号没有足够钱%s'%acctid
raise Exception('账号没有足够钱%s'%acctid)
finally:
cursor.close()
def reduce_money(self,acctid,money):
cursor=self.conn.cursor()
try:
sql='update hh 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 hh 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:
print '!!!'
self.conn.rollback()#如果上面的哪一点出现错误就回滚操作,对数据库不做任何改变
print str(e)
raise e#抛出错误
if __name__=='__main__':
source_acctid='12'#转账的人
target_acctid='13'#收账的人
money='100'#要转到金额
conn=pymssql.connect('localhost','sa','268186','we',charset='utf8')#连接数据库
ty_money=TransferMoney(conn)#获取对象
try:
ty_money.transfer(source_acctid,target_acctid,money)
except Exception as e:#获取错误信息 ,并打印出来
print 'chu xian de wen ti'+str(e)
finally:
conn.close()#关闭数据库
所建的数据库:
acctid money
-------------------------------------------------- --------------------------------------------------
12 110
13 10
14 90
15 100
执行结果:
check_acct_available:select * from hh where acctid=12
[(u'12', u'110')]
check_acct_available:select * from hh where acctid=13
[(u'13', u'10')]
has_enough_money:select * from hh where acctid=12 and money>100
reduce_money:update hh set money=money-100 where acctid=12
add_money:update hh set money=money+100 where acctid=13
执行完以上代码之后的数据库:
acctid money
-------------------------------------------------- --------------------------------------------------
12 10
13 110
14 90
15 100