使用configparser模块来处理conf、ini配置文件。
安装命令:pip install configparser
一个为mysql.conf
,是MySQL的连接配置;另一个是Python代码,用于读取某张表的具体内容。
https://segmentfault.com/a/1190000020216010
[mysql]
db_host=localhost
db_port=3306
db_user=root
db_password=
db_database=school
读取测试:
from configparser import ConfigParser
import pymysql
config = ConfigParser()
config.read("mysql.conf")
host = config.get("mysql","db_host")
port = config.get("mysql","db_port")
user = config.get("mysql","db_user")
password = config.get("mysql","db_password")
database = config.get("mysql","db_database")
print("host",type(host),host)
print("port",type(port),port)
db = pymysql.connect(host=host,port=port,user=user,password=password,database=database)
cursor = db.cursor()
cursor.execute("select * from datebase_name")
for row in cursor.fetchall():
print(row)
cursor.close()
db.close()
更多详情:https://www.jianshu.com/p/aadd86f8d38e