学习Python操作MySQL过程中完成一个实例:实现一个银行转账小功能!顺便也供自己往后查看!
网上关于利用Python创建MySQL数据库的实例太多太杂,很多博客都讲得模棱两可,实际上我查阅资料发现MySQLdb是对应Python2.x版本,而pymysql是对应Python3.x版本的!本次所用的Python是3.x版本的!!
代码中注释很明确!!不懂的小白可以看看我的注释,大神可以绕路!!
注:菜鸟一枚!若有不对的地方可以和我一并探讨!
图片关于Python DB API访问SQL的思路图
注:图片是案例的思路!!
话不多说,直接上代码!!
import sys
import pymysql
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
class TransferMoney(object):
def __init__(self, conn):
self.conn = conn
"""转账函数"""
def transfer(self, source_acctid, target_acctid, money):
try:
# 判断账户是否存在的函数?
self.check_acct_available(source_acctid) # source_acctid 是传入的参数变量,以下类似
self.check_acct_available(target_acctid)
# 判断账户是否有足够的钱的函数?
self.has_enough_money(source_acctid, money)
# 转账操作函数调用
self.reduce_money(source_acctid, money)
self.add_money(target_acctid, money)
# 转账成功提交事务
self.conn.commit()
except Exception as e:
# 撤销数据库的执行,回滚事务
self.conn.rollback()
raise e # 异常抛出
"""检测账户是否存在?"""
def check_acct_available(self, acctid):
cur = self.conn.cursor() # 创建光标
try:
# 查询账户名为acctid的详细信息
select_sql = "select * from table_account where acctid='%s'"% (acctid) # 本人输入的是字符串,sql语法要求'%s'
cur.execute(select_sql)
#print("execute sql:%s" % (select_sql))
# 返回所选的结果集
res = cur.fetchall()
if len(res) != 1: # 若结果集的条数不为1,账号不存在
raise Exception("帐号%s不存在" % (acctid))
finally:
cur.close() # 出现问题需要关闭cursor
"""检测账户是否有足够的钱"""
def has_enough_money(self, acctid, money):
cur = self.conn.cursor()
try:
select_sql = "select money from table_account where acctid='%s'" % (acctid)
cur.execute(select_sql)
#print('has_enough_money sql: %s' % (select_sql))
# 返回money的结果集
res = cur.fetchall()
if len(res) != 1:
now_money = int(res[0][0])
if int(now_money) < int(money):
raise Exception("账户'%s'没有足够的钱,目前金额为 %d" % (acctid, now_money))
finally:
cur.close()
"""给其他账户进行转账操作"""
def reduce_money(self, acctid, money):
cur = conn.cursor()
try:
update_sql = "update table_account set money=money-%s where acctid='%s'" % (money, acctid) # 更新数据库,假如转账¥100,那么该账户-¥100
cur.execute(update_sql)
print('转账人:%s' % (acctid))
except Exception as e:
print("转账失败:", e)
finally:
cur.close()
def add_money(self, acctid, money):
cur = conn.cursor()
try:
update_sql = "update table_account set money=money+%s where acctid='%s'" % (money, acctid)
cur.execute(update_sql)
print('收账人:%s' % (acctid))
except Exception as e:
print("转账失败:", e)
finally:
cur.close()
if __name__ == "__main__":
conn = pymysql.connect(host='localhost', user='root',passwd='******', charset='utf8')
my_list = [['Mata', 200], ['Dalot', 50], ['Fred', 350], ['La', 450]]
df_list = pd.DataFrame(my_list, columns=['acctid', 'money'])
print(df_list)
def create_database():
"""创建数据库"""
cur = conn.cursor()
cur.execute('drop database if exists transfer_money') # 若数据库存在则删除
cur.execute("create database transfer_money character set utf8 ;")
print("数据库创建成功")
cur.execute("use transfer_money;")
#cur.execute("drop table if exists account;")
#cur.execute("create table account(name char(20), money char(20))character set utf8;")
#print("表格创建成功")
cn = create_engine('mysql+pymysql://root:lemon0610@localhost:3306/transfer_money?charset=utf8')
df_list.to_sql('table_account', cn, index=False)
create_database()
# 传入三个参数变量
source_acctid = input("Input source_acctid")
target_acctid = input("Input target_acctid")
money = int(input("Input tansfer money "))
trans_money = TransferMoney(conn) # 定义转账这一类,实例化
try:
trans_money.transfer(source_acctid, target_acctid, money)
print("转账成功,转账金额:¥%s"%(money))
except Exception as e:
print("转账出现问题:", e)
finally:
conn.close() # 关闭连接,释放网络资源
操作流程:
原数据库:
现数据库:
代码思路:
- 创建list生成DataFrame;
- 创建MySQL的Database;
- pandas2MySQL;
- 调用转账函数完成转账操作!!