Python 数据库配置文件
2022/4/2 2:19:43
本文主要是介绍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的当前文件地址
- 暂未优化,需确保配置和设置配置文件的相对路径一致
这篇关于Python 数据库配置文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python