python 如何通过yaml文件连接mysql

背景:

python 连接mysql数据库,一般简单的参数写死方式如下:

db = pymysql.connect(host='127.0.0.1',port=3306,user='root',password='password123',database='learning',charset='utf8')

有时候需要连接不同的数据库地址,在代码中直接修改,容易出错。数据库连接参数一般不会变动,所以我们可以选择写成配置文件。这里介绍下,如何通过写yaml配置文件连接mysql。

思路:

  • 将参数写入yaml文件

  • 创建类和方法读取yaml文件

  • 连接数据库,调用方法传入参数

详细步骤:

  1. 创建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

  1. 创建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
  1. 创建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")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值