Python操做MySQL案例

   最近都在學習Python代碼,但願學會Python後,能給我帶來更高的工做效率,因此天天堅持學習和拷代碼,下面是一個Python操做MySQL的一個實例,該實例可讓更多的人更好了解MySQLdb模塊的使用。我是Python菜鳥,經過學習別人的實例來讓本身學到更多Python知識。html

 

案例:用Python實現銀行轉帳python

1、在MySQL建立一張表account表,而後在裏面插入兩條數據:mysql

mysql> show create table account\G
*************************** 1. row ***************************
       Table: account
Create Table: CREATE TABLE `account` (
  `userid` int(11) DEFAULT NULL COMMENT '帳號ID',
  `money` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
1 row in set (0.02 sec)

mysql> 

當前數據:sql

mysql> select * from account;
+--------+-------+
| userid | money |
+--------+-------+
|      1 |   200 |
|      2 |   200 |
+--------+-------+
2 rows in set (0.00 sec)

mysql> 

 

 編輯腳本money.py文件,運行些腳本須要安裝MySQLdb模塊,詳細安裝和基本的使用能夠參考個人博客:http://www.cnblogs.com/xuanzhi201111/p/5144982.html函數

#!/usr/bin/env python
#coding:utf-8
#name:money.py

import sys
import MySQLdb


class TransferMoney(object):
    def __init__(self,conn):
        self.conn = conn

#用於檢查是否存在轉帳用戶或者被轉帳用戶
    def check_user_exist(self, userid):
        cursor = self.conn.cursor()
        try:
            sql = "select * from account where userid = %s" % userid
            cursor.execute(sql)
            print "\033[;32m驗證用戶是否存在: \033[0m" + sql
        except Exception,e:
            raise Exception('執行sql錯誤:%s' % e)
        else:
            rs = cursor.fetchall()
            if len(rs) != 1:
                raise Exception ("帳號%s不存在" % userid)
        finally:
            cursor.close()
            

#用於檢查是用戶是否有足夠的錢轉給別人
    def has_enough_money(self,source_userid,money):
        cursor = self.conn.cursor()
        try:
            sql = "select * from account where userid = %s and money > %s" % (source_userid,money)
            cursor.execute(sql)
            print "\033[;32m檢查是否有足夠的錢: \033[0m" + sql
        except Exception,e:
            raise Exception('執行sql錯誤:%s' % e)
        else:
            rs = cursor.fetchall()
            if len(rs) != 1:
                raise Exception ("帳號%s餘額不足" % source_userid)
        finally:
            cursor.close()

#用於減去轉掉的部份金額
    def reduce_money(self,source_userid,money):
        cursor = self.conn.cursor()
        try:
            sql = "update account set money = money - %s where userid=%s" % (money,source_userid)
            cursor.execute(sql)
            print "\033[;32m從源帳戶%s里扣掉對應的金額: \033[0m" % (source_userid)  + sql
        except Exception,e:
            raise Exception('執行sql錯誤:%s' % e)
        else:
            rs = cursor.rowcount
            if rs!=1:
                raise Exception("帳號%s減款失敗" % source_userid)
        finally:
            cursor.close()
        
#用於把別人轉過來的錢加到目標用戶的金額上
    def add_money(self,target_userid,money):
        cursor=self.conn.cursor()
        try:
            sql="update account set  money = money + %s where userid=%s" % (money,target_userid)   
            cursor.execute(sql)
            print '\033[;32m目標帳戶%s加上轉過來的金額:\033[0m' % (target_userid) + sql
        except Exception,e:
            raise Exception('執行sql錯誤:%s' % e)
        else:
            rs=cursor.rowcount
            if rs!=1:
                raise Exception("帳號%s加錢失敗" % target_userid)
        finally:
            cursor.close()

#用於轉帳後的查詢帳號的金額
    def check_money(self,source_userid):
        cursor=self.conn.cursor()
        try:
            sql="select * from account where userid=%s" % (source_userid)
            cursor.execute(sql)
        except Exception,e:
            raise Exception('執行sql錯誤:%s' % e)
        else:
            rs = cursor.fetchall()
            for row in rs:
                print "userid=%d, 如今的金額=%d" % row
        finally:
            cursor.close()

#主函數,調用以上的函數造成一個事務
    def transfer(self, source_userid, target_userid, money):
        try:
            self.check_user_exist(source_userid)
            self.check_user_exist(target_userid)
            self.has_enough_money(source_userid,money)
            self.reduce_money(source_userid,money)
            self.add_money(target_userid,money)
            self.conn.commit()
            self.check_money(source_userid)
            self.check_money(target_userid)
        except Exception as e:
            self.conn.rollback()
            raise e


if __name__ == '__main__':
    source_userid = sys.argv[1]
    target_userid = sys.argv[2]
    money = sys.argv[3]


    conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='123456',port=3306,db='python')
    tr_money = TransferMoney(conn)


    try:
        tr_money.transfer(source_userid,target_userid,money)
    except Exception as e:
        print "\033[;31m出現問題:\033[0m" + str(e)
    finally:
        conn.close()

 

代碼驗證:學習

從帳號1 轉帳100塊給帳號 2:fetch

[root@Python test]# python money.py  1 2 100
驗證用戶是否存在: select * from account where userid = 1
驗證用戶是否存在: select * from account where userid = 2
檢查是否有足夠的錢: select * from account where userid = 1 and money > 100
從源帳戶1里扣掉對應的金額: update account set money = money - 100 where userid=1
目標帳戶2加上轉過來的金額:update account set  money = money + 100 where userid=2
userid=1, 如今的金額=100
userid=2, 如今的金額=300

從帳號 1 轉500給帳號 2,會出現餘額不足優化

[root@Python test]# python money.py  1 2 500
驗證用戶是否存在: select * from account where userid = 1
驗證用戶是否存在: select * from account where userid = 2
檢查是否有足夠的錢: select * from account where userid = 1 and money > 500
出現問題:帳號1餘額不足

從帳號 2 轉帳200塊給帳號 1spa

[root@Python test]# python money.py  2 1 200
驗證用戶是否存在: select * from account where userid = 2
驗證用戶是否存在: select * from account where userid = 1
檢查是否有足夠的錢: select * from account where userid = 2 and money > 200
從源帳戶2里扣掉對應的金額: update account set money = money - 200 where userid=2
目標帳戶1加上轉過來的金額:update account set  money = money + 200 where userid=1
userid=2, 如今的金額=100
userid=1, 如今的金額=300

能夠看到正常的轉帳了,初學Python,還有不少須要優化的地方,但願你們指出個人不足,讓我更好更快的成長,同時也但願你們一塊兒把Python學好code

 

參考資料:

    http://www.imooc.com/

 

 

做者:陸炫志

出處:xuanzhi的博客 http://www.cnblogs.com/xuanzhi201111

您的支持是對博主最大的鼓勵,感謝您的認真閱讀。本文版權歸做者全部,歡迎轉載,但請保留該聲明。

相關文章
相關標籤/搜索