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

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

详细代码如下:

  

 1 import pymysql
 2 from config_parser import cconfigparser
 3 
 4 class connectMySQL(object):
 5     def  __init__(self,hostname,user,password,dbname,port):
 6         db_config = {
 7             'host': hostname,
 8              'port': port,
 9              'user': user,
10              'password': password,
11              'db': dbname
12             }
13         self.conn = pymysql.connect(**db_config)
14     def get_cursor(self):
15         return self.conn.cursor()
16 
17     def querydb(self,sqlstring):
18         cursor = self.get_cursor()
19         try:
20             cursor.execute(sqlstring)
21             results = cursor.fetchall()
22             for row in results:
23                 print(row)
24         except:
25             self.logger.error('Error:unable to fetch data')
26 if __name__ == '__main__':
27 
28     cccon = cconfigparser('C:\\Users\\lenovo\\Desktop\\config.ini')
29     host = cccon.get('db_config_CD','host')
30     port = int(cccon.get('db_config_CD','port'))
31     print('port',port)
32     user = cccon.get('db_config_CD','user')
33     password = cccon.get('db_config_CD','password')
34     db = cccon.get('db_config_CD','db')
35 
36     sqlstring = 'select table_name from information_schema.tables where table_schema=\'jac\''
37     c = connectMySQL(host, user, password, db, port)
38     c_chendu = c.querydb(sqlstring)

猜你喜欢

转载自www.cnblogs.com/jiyanjiao-702521/p/9435578.html