34 lines
1.2 KiB
Python
34 lines
1.2 KiB
Python
#!/usr/local/bin/python3
|
|
# -*- coding: utf-8 -*-
|
|
|
|
import libs.common as common
|
|
import MySQLdb
|
|
|
|
# 创建新数据库。
|
|
def create_new_database():
|
|
with MySQLdb.connect(common.MYSQL_HOST, common.MYSQL_USER, common.MYSQL_PWD, "mysql", charset="utf8") as db:
|
|
try:
|
|
create_sql = " CREATE DATABASE IF NOT EXISTS %s CHARACTER SET utf8 COLLATE utf8_general_ci " % common.MYSQL_DB
|
|
print(create_sql)
|
|
db.autocommit(on=True)
|
|
db.cursor().execute(create_sql)
|
|
except Exception as e:
|
|
print("error CREATE DATABASE :", e)
|
|
|
|
|
|
# main函数入口
|
|
if __name__ == '__main__':
|
|
|
|
# 检查,如果执行 select 1 失败,说明数据库不存在,然后创建一个新的数据库。
|
|
try:
|
|
with MySQLdb.connect(common.MYSQL_HOST, common.MYSQL_USER, common.MYSQL_PWD, common.MYSQL_DB,
|
|
charset="utf8") as db:
|
|
db.autocommit(on=True)
|
|
db.cursor().execute(" select 1 ")
|
|
print("########### db exists ###########")
|
|
except Exception as e:
|
|
print("check MYSQL_DB error and create new one :", e)
|
|
# 检查数据库失败,
|
|
create_new_database()
|
|
# 执行数据初始化。
|