1.此篇是以上篇为基础,仍以上篇的配置文件为例此处查看上篇配置文件解析:
[rds_mysql]
ip=localhost
port=3306
db=test1,test2
user=root
passwd=123456
enable=1
2.自定义数据库的映射列表:
#value值为数据库名,key值为库所在的文件名
DB_tag = {
'test1': 'rds_mysql',
'test2': 'rds_mysql',
}
3.动态链接函数:
import mysqldb
#自定义配置字典,一般常用数据库可以写死,有新增可以手动添加上去
DB_tag = {
'test1': 'rds_mysql',
'test2': 'rds_mysql',
}
#动态链接函数,传入配置字典和想要连接的数据库名
def link_dynamic_DB(DB_tag,DB_name):
'''dynamic link db'''
#读取数据库的配置文件
read_DB = {
'host': conf.get(DB_tag[DB_name], "ip"),
'username': conf.get(DB_tag[DB_name], "user"),
'password': conf.get(DB_tag[DB_name], "passwd"),
'port': conf.get(DB_tag[DB_name], "port"),
'database': DB_name,
}
#利用mysqldb模块连接数据库
conn = MySQLdb.connect(host=read_DB['host'], port=int(read_DB['port']), user=read_DB['username'],
passwd=read_DB['password'], db=read_DB['database'], charset='utf8')
cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
return cursor, conn
4.调用函数:
'''以上第三步中,对于不常改动的数据库或者配置文件的DB_tag可以直接写在函数内部,
这样调用的时候只需要传入一个数据库名就可以
(技术够硬的同学也可以想想怎么利用传入的数据库名到配置文件里寻址找到文件名,
这样DB_tag都可以不需要)'''
cursor, conn = link_dynamic_DB('test1')