python通过配置文件连接数据库

时间:2023-03-10 07:44:08
python通过配置文件连接数据库

今天主要是通过读取配置文件(ini文件)获取数据库表的ip,端口,用户,密码,表名等,使用pysql来操作数据库,具体的ini配置文件的操作参见我另一篇博客:https://www.cnblogs.com/jiyanjiao-702521/p/9420343.html

详细代码如下:

  

 import pymysql
from config_parser import cconfigparser class connectMySQL(object):
def __init__(self,hostname,user,password,dbname,port):
db_config = {
'host': hostname,
'port': port,
'user': user,
'password': password,
'db': dbname
}
self.conn = pymysql.connect(**db_config)
def get_cursor(self):
return self.conn.cursor() def querydb(self,sqlstring):
cursor = self.get_cursor()
try:
cursor.execute(sqlstring)
results = cursor.fetchall()
for row in results:
print(row)
except:
self.logger.error('Error:unable to fetch data')
if __name__ == '__main__': cccon = cconfigparser('C:\\Users\\lenovo\\Desktop\\config.ini')
host = cccon.get('db_config_CD','host')
port = int(cccon.get('db_config_CD','port'))
print('port',port)
user = cccon.get('db_config_CD','user')
password = cccon.get('db_config_CD','password')
db = cccon.get('db_config_CD','db') sqlstring = 'select table_name from information_schema.tables where table_schema=\'jac\''
c = connectMySQL(host, user, password, db, port)
c_chendu = c.querydb(sqlstring)