Python操作MySQL模擬銀行轉賬
阿新 • • 發佈:2020-01-09
今天在網上學習了有關於python操作MySQL的相關知識,在此做些總結。python操作資料庫還是相對比較簡單的,由於python統一了各個資料庫的介面程式,也就是所謂的Python DB,所以無論使用何種資料可,都可以用統一的介面對資料庫進行操作。操作中主要涉及connection物件的操作和cursor的操作,前者主要是為了建立起python與資料庫的資料交換通道,後者則是訪問資料的遊標,也可以理解為指標。資料庫的相關結構化語言在Python中均是以字串的形式呈現的。另外注意rollback的重要性,一旦操作失敗,所有操作都要回滾到之前的狀態,否則會發生錯誤。
另外,在編寫例項的時候,對於面向物件的程式設計思路又有了新的認識,自頂向下的程式編寫模式非常有利於拆分程式的功能,分而治之。面向物件的封裝性在此提醒的淋漓盡致!
程式碼如下,在原有基礎上,我又增加了新增記錄的功能。
#coding=utf8 import MySQLdb import sys class TranseferMonet(object): def __init__(self,conn): self.conn = conn def createNewUser(self,userID,money): cursor = self.conn.cursor() try: sql = 'INSERT account VALUES(%s,%s)' %(str(userID),str(money)) cursor.execute(sql) self.conn.commit() except Exception as e: self.conn.rollback() raise e def transferMoney(self,transeferID,recivierID,money): try: self.checkID(transeferID) self.checkID(receiverID) self.checkEnoughMoney(transferID,money) self.subMoney(transferID,money) self.addMoney(receiverID,money) self.conn.commit() except Exception as e: self.conn.rollback() raise e def checkID(self,userID): cursor = self.conn.cursor() try: sql = 'SELECT userID FROM account WHERE userID = %s' %str(userID) cursor.execute(sql) rs = cursor.fetchall() if len(rs) != 1: raise Exception("ID錯誤!") finally: cursor.close() def checkEnoughMoney(self,transferID,money): cursor = self.conn.cursor() try: sql = 'SELECT money FROM account WHERE userID = %s and money >= %s' %(str(transferID),str(money)) cursor.execute(sql) rs = cursor.fetchall() if len(rs) != 1: raise Exception("餘額不足!") finally: cursor.close() def subMoney(self,money): cursor = self.conn.cursor() try: sql = 'UPDATE account SET money = money-%s WHERE userID = %s' %(str(money),str(transferID)) cursor.execute(sql) if cursor.rowcount != 1: raise Exception('減款失敗!') finally: cursor.close() def addMoney(self,receiverID,money): cursor = self.conn.cursor() try: sql = 'UPDATE account SET money = money+%s WHERE userID = %s' %(str(money),str(receiverID)) cursor.execute(sql) if cursor.rowcount != 1: raise Exception('加款失敗!') finally: cursor.close() if __name__=="__main__": transferID = 2002 receiverID = 2001 money = 300 newID = 2003 newmoney = 900 conn = MySQLdb.connect(host = '127.0.0.1',port = 3306,user = 'root',passwd = '914767195',db = 'test',charset = 'utf8') trMoney = TranseferMonet(conn) try: trMoney.transferMoney(transferID,money) except Exception as e: print "轉賬錯誤"+str(e) try: trMoney.createNewUser(newID,newmoney) except Exception as e: print "建立使用者失敗!"+str(e) finally: conn.close()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。