先安裝 pip, python 的包管理工具
安裝
sudo pip install mysql-connector-python
連接數據庫
#!/usr/bin/python # -*- coding: UTF-8 -*- import mysql.connector db = mysql.connector.connect( host = '127.0.0.1', port = 3306, user = 'root', passwd = 'gou110422', database = 'test', charset = 'utf8' ) cursor = db.cursor() sql_query = 'select name,money from user;' #執行sql 語句 cursor.execute(sql_query) print cursor.rowcount rs = cursor.fetchall() #cursor.rowcount 表中受影響數據個數 #fetchall() 獲取所有數據 #fetchone() 獲取一條數據 #fetchmany(3) 獲取 3個數據 print rs for item in rs: print 'name: %s money: %s' % item print '成功' #cursor.close() #關閉游標 db.close()
api:http://www.runoob.com/python3/python-mysql-connector.html
示例:
# -*- coding: UTF-8 -*- import mysql.connector class TransferMoney(): def __init__(self, db): self.db = db #轉賬流程 def transferMoney(self, id, targetId, money): try: self.checkTargetUser(targetId) #檢查被轉賬賬號是否存在 self.checkMoney(id, money) #檢查余額是否足夠 self.transfer(id, targetId, money) #轉賬 self.db.commit() #提交修改 except Exception as e: self.db.rollback() #回滾事物 raise e #檢查被轉賬賬號是否存在 def checkTargetUser(self, id): try: cursor = self.db.cursor() sql_query = 'select * from user where id=%s;' % id cursor.execute(sql_query) rs = cursor.fetchall() if len(rs) != 1: raise Exception('轉賬賬戶不存在!') else: print '轉賬賬戶存在!' except mysql.connector.Error as e: raise Exception('檢查被轉賬賬戶是否存在出錯:' + str(e)) finally: cursor.close() #檢查轉賬金額 def checkMoney(self, id, money): try: cursor = self.db.cursor() sql_query = 'select * from user where id=%s and money > %s;' % (id,money) cursor.execute(sql_query) rs = cursor.fetchall() if len(rs) != 1: raise Exception('轉賬賬戶余額不足!') else: print '轉賬方金額充足!' except mysql.connector.Error as e: raise Exception('檢查金額出錯::' + str(e)) finally: cursor.close() #轉賬 def transfer(self, id, targetId, money): try: cursor = self.db.cursor() #自己先減去轉賬金額 sql_query = 'update user set money=money-%s where id=%s;' % (money,id) rs = cursor.execute(sql_query) if cursor.rowcount != 1: raise Exception('賬號%s減款失敗!' % id) #目標賬戶加上轉賬金額 sql_query1 = 'update user set money=money+%s where id=%s;' % (money, targetId) cursor.execute(sql_query1) if cursor.rowcount != 1: raise Exception('賬號%s加款失敗!' % targetId) print '成功轉賬%s元!' % money except mysql.connector.Error as e: raise Exception('轉賬出錯:' + str(e)) finally: cursor.close() if __name__ == '__main__': db = mysql.connector.connect(host='127.0.0.1',port=3306,user='root',passwd='gou110422',database='test',charset='utf8') base = TransferMoney(db) try: id,targetId,money = (1,2,100) base.transferMoney(id, targetId, money) except Exception as e: print '異常:',e finally: db.close() #cursor.execute執行sql 語句 #cursor.rowcount 表中受影響數據個數 放在execute()之后 #fetchall() 獲取所有數據 #fetchone() 獲取一條數據 #fetchmany(3) 獲取 3個數據 #db.commit() 數據表內容有更新,必須使用到該語句 #cursor.close() #關閉游標