1. 程式人生 > >python-mysql超簡單銀行轉賬

python-mysql超簡單銀行轉賬

1首先先建資料庫bank,資料結構表的名稱為accoment:


2.python與mysql互動程式碼如下:

# coding =utf-8
# 1.匯入模組
from pymysql import *
import sys
import pymysql

# 2.接受命令列引數
if __name__ == '__main__':
    source_acctid = '11'
    target_acctid = '12'
    number = input("請輸入您要轉賬的金額:")
    mony = int(number)

    # 獲取資料庫連結
    conn = connect(
        user='root',
        password='mysql',
        database='bank',
        charset='utf8',
        use_unicode=True
    )

    # 獲取遊標
    cursor = conn.cursor()

    # 查詢餘額
    sql = u'select money from accoment where acctid='

    # 拼接字串
    sql1 = sql + source_acctid

    # 列印看一下拼出來的效果
    print(sql1)
    cursor.execute(sql1)

    # 執行sql獲取到餘額,返回的是一個tuple,如(100,)
    f = cursor.fetchone()

    print(f)

    # 判斷餘額大於轉出金額,就進行轉賬
    if f[0] > mony:
        # 寫sql
        sql = u'select money from accoment where acctid=' + target_acctid
        cursor.execute(sql)
        x = cursor.fetchone()
        # 轉入賬戶+
        money = x[0] + mony
        # 轉出賬戶
        money1 = f[0] - mony
        sql2 = u'update accoment set money=%s where acctid= %s'
        sql3 = u'update accoment set money=%s where acctid=%s'
        # 執行
        cursor.execute(sql2, [money, target_acctid])
        cursor.execute(sql3, [money1, source_acctid])
        conn.commit()

        # 關閉遊標
        cursor.close()
    else:
        # 其他情況拋異常
        raise Exception('Not have enough money')
    print(conn)
    print(cursor)
    conn.close()

3.執行即可