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:# 写sqlsql = u'select money from accoment where acctid=' + target_acctidcursor.execute(sql)x = cursor.fetchone()# 转入账户+money = x[0] + mony# 转出账户money1 = f[0] - monysql2 = 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.运行即可