import pymysql
def get_db_connect(host, port, user, password, db, charset='utf8mb4'):
"""连接数据库并返回数据库连接-数据库不存在则创建数据库"""
db_conf = dict(host=host, port=port, user=user, password=password, db=db,
charset=charset, autocommit=True, cursorclass=pymysql.cursors.DictCursor)
try:
return pymysql.connect(**db_conf)
except pymysql.err.OperationalError as ex:
if 'Unknown database' in ex.args[1]:
db_conf.pop('db')
with pymysql.Connection(**db_conf) as conn:
conn.cursor().execute('CREATE DATABASE %s' % db)
db_conf['db'] = db
return pymysql.connect(**db_conf)