【实例】 python数据库编程
来源:互联网 发布:知乎布鲁塞尔自由大学 编辑:程序博客网 时间:2024/06/11 18:46
#coding:utf8#转账系统import sysimport MySQLdbclass TransferMoney(object): def __init__(self, conn): self.conn = conn def check_acct_available(self, id): cursor = self.conn.cursor() try: sql = "select * from account where acctid=%s" % id print sql cursor.execute(sql) rs = cursor.fetchall() if len(rs) != 1: raise Exception("id %s is not existed" % id) finally: cursor.close() def has_enough_money(self, id, money): cursor = self.conn.cursor() try: sql = "select * from account where acctid=%s and money>%s" % (id, money) print sql cursor.execute(sql) rs = cursor.fetchall() if len(rs) != 1: raise Exception("id %s doesn't have enough money" % id) finally: cursor.close() def reduce_money(self, id, money): cursor = self.conn.cursor() try: sql = "update account set money = money-%s where acctid=%s" % (money, id) print sql cursor.execute(sql) if cursor.rowcount != 1: raise Exception("id %s reduces unsuccessfully" % id) finally: cursor.close() def add_money(self, id, money): cursor = self.conn.cursor() try: sql = "update account set money = money + %s where acctid = %s" % (money, id) print sql cursor.execute(sql) if cursor.rowcount != 1: raise Exception("id %s adds unsuccessfully" % id) finally: cursor.close() def transfer(self,source_id, target_id, money): try: self.check_acct_available(source_id) self.check_acct_available(target_id) self.has_enough_money(source_id, money) self.reduce_money(source_id, money) self.add_money(target_id, money) self.conn.commit() except Exception as e: self.conn.rollback() raise eif __name__ == "__main__": source_id = sys.argv[1] target_id = sys.argv[2] money = sys.argv[3] conn = MySQLdb.Connect(host='127.0.0.1',user='root', passwd = '', \ port = 3306, db = 'python') tr_money = TransferMoney(conn) try: tr_money.transfer(source_id, target_id, money) except Exception as e: print "出现问题"+str(e) finally: conn.close()
0 0
- 【实例】 python数据库编程
- python数据库操作实例
- python udp编程实例
- mapreduce python编程实例
- spark编程python实例
- Python编程实例1
- python数据库编程_sqlite
- python数据库编程_sqlite
- python mysql数据库编程
- python数据库编程
- Python 的数据库编程
- python数据库编程
- python数据库编程
- Python数据库编程
- Python数据库编程
- python操作mysql数据库实例
- Python操作MySQL数据库实例
- Python操作MySQL数据库实例
- 前端优化建议
- Java 异常处理
- 项目经理面试中常被问到的12问题
- 【红宝书笔记】原型模式-prototype
- HashMap实现原理分析
- 【实例】 python数据库编程
- Android开发应用程序发布到Google Play步骤
- Git 常用命令速查表
- JSP编译成Servlet(一)语法树的生成——语法解析
- string类 sort Educational Codeforces Round 9 C. The Smallest String Concatenation
- PAT (Advanced Level) Practise 1065 A+B and C (64bit) (20)
- 用三种方式取出给定字符串中的目标字串
- C++虚继承(二) --- C++ 对象的内存布局(上)(陈皓)
- QML中的AnchorChanges锚布局改变元素