本节通过PyMysql驱动编写sql语句来操作数据库。但是通过编写sql语句生成数据库比较麻烦,本节为了简化这一流程,避免直接编写sql语句。
一、目录结构:
- mysql_db.py文件对数据库进行封装操作,主要包含连接数据库、执行sql语句、数据库的关闭操作,将sql语句单独出来,而不用以后每个接口中调用;
- db_config.ini文件为数据库的配置内容;
二、数据库操作封装
db_config.ini文件
[mysqlconf]
host=127.0.0.1
port=3306
user=root
password=111111
db_name=guest_test
mysql_db.py文件
# -*-encoding=utf-8-*-
import pymysql.cursors
from os.path import abspath, dirname
#configparser库用来读取ini类型的配置文件
import configparser as cparser
#=======================读取db_config.ini文件设置=======================
# 配置文件的绝对路径
# base_dir = str(os.path.dirname(os.path.dirname(__file__)))
# base_dir = base_dir.replace('\\','/')
# file_path = base_dir + "/db_config.ini"
# print(file_path)
base_dir = dirname(dirname(abspath(__file__)))
base_dir = base_dir.replace('\\', '/')
file_path = base_dir + "/db_config.ini"
print(file_path)
#初始化
cf = cparser.ConfigParser()
#读取配置文件
cf.read(file_path)
host = cf.get("mysqlconf","host")
port = cf.get("mysqlconf","port")
user = cf.get("mysqlconf","user")
password