Python 数据库配置文件
config.ini
[DATABASE]
# 数据库配置
host = tmysql.***.com
username = kevin
password =******
port = 3306
database = HT_IMDB
readConfig.py
import configparser
from pathlib import Path
class ReadConfig():
def __init__(self):
configDir = Path.cwd().parent.joinpath("config.ini")
# 配置文件地址
self.cf = configparser.ConfigParser()
self.cf.read(configDir)
def getHTTPValue(self, name):
value = self.cf.get("HTTP", name)
return value
def getDBValue(self, name):
value = self.cf.get("DATABASE", name)
return value
configDB.py
import pymysql
import readConfig
localReadConfig = readConfig.ReadConfig()
class myDB:
def __init__(self):
self.host = localReadConfig.getDBValue("host")
self.username = localReadConfig.getDBValue("username")
self.password = localReadConfig.getDBValue("password")
self.port = int(localReadConfig.getDBValue("port"))
self.database = localReadConfig.getDBValue("database")
def connect_mysql(self):
#连接数据库
conn = pymysql.connect(host=self.host,port=self.port,user=self.username,password=self.password,database=self.database)
#使用cursor()方法创建一个游标对象
cursor = conn.cursor()
#使用execute()方法执行SQL语句
cursor.execute("SELECT * FROM HT_VIRTUAL_GIFT")
#使用fetall()获取全部数据
data = cursor.fetchall()
cursor.close()
conn.close()
return data
test = myDB()
data = test.connect_mysql()
print(data)
问题
- 在configDB下查询不到config.ini文件,在readConfig下没有问题
分析
- 用pathlib读取的ini文件地址错误,没有获取readConfig的当前文件地址
- 暂未优化,需确保配置和设置配置文件的相对路径一致