背景:
python 连接mysql数据库,一般简单的参数写死方式如下:
db = pymysql.connect(host='127.0.0.1',port=3306,user='root',password='password123',database='learning',charset='utf8')
有时候需要连接不同的数据库地址,在代码中直接修改,容易出错。数据库连接参数一般不会变动,所以我们可以选择写成配置文件。这里介绍下,如何通过写yaml配置文件连接mysql。
思路:
将参数写入yaml文件
创建类和方法读取yaml文件
连接数据库,调用方法传入参数
详细步骤:
创建mysqlConnect.yaml 文件,写入数据如下
# 数据库配置
# 键值对格式 dev:{host:127.0.0.1,port:3306,user:root,password:password123,database:learning,charset:utf8}
dev:
host: 127.0.0.1
port: 3306
user: root
password: password123
database: learning
charset: utf8
prod:
host: 127.0.0.1
port: 3307
user: root
password: password123
database: learning-prod
charset: utf8
创建handle_yaml.py文件,创建类和方法读取yaml文件
import yaml
class MysqlConnectYaml: # 操作mysqlConnect.yaml文件的
def get_yaml_mysql(self,file_path):
file = open(file_path,'r',encoding='utf-8
res = yaml.safe_load(file)
file.close()
return res
def get_dev(self, env, file_path):
resp = self.get_yaml_mysql(file_path)
print(type(resp)) # 是字典格式
if env in "prod":
return resp["prod"]
else:
return resp["dev"]
""
if __name__ == '__main__':
db_yaml = MysqlConnectYaml()
db_connect = db_yaml.get_dev("dev","../data/mysqlConnect.yaml") # 返回是字典格式,所以直接下标取数据
print(type(db_yaml), type(db_connect))
print(db_connect)
print(db_connect["port"])
输出结果
<class 'dict'>
<class '__main__.MysqlConnectYaml'> <class 'dict'>
{'host': '127.0.0.1', 'port': 3306, 'user': 'root', 'password': 'password123', 'database': 'learning', 'charset': 'utf8'}
3306
创建handle_mysql.py文件,调用相关方法
import pymysql
from utils.handle_yaml import MysqlConnectYaml
class MysqlConnections:
# 方法二:通过yaml配置
def __init__(self,env,file_path):
self.db_yaml = MysqlConnectYaml() # 实例化
self.db_connect = self.db_yaml.get_dev(env,file_path)
# 读取配置参数
self.db = pymysql.Connect(host=self.db_connect["host"],port=self.db_connect["port"],user=self.db_connect["user"],password=self.db_connect["password"],database=self.db_connect["database"],charset=self.db_connect["charset"])
self.cursor = self.db.cursor()
if __name__ == '__main__':
db = MysqlConnections("dev", "../data/mysqlConnect.yaml")