python 创建mysql数据库


昨天用shell脚本创建数据库,涉及java调用,比较折腾,改用python直接创建数据库,比较方便,好了,直接上代码,相关注释也添加了

# _*_encoding:UTF-8_*_
import MySQLdb

db_host = ''
db_user = ''
db_pw = ''
db_name = 'vdt'


def cre_db(host, user, pw, name):
try:
# 数据库连接
db = MySQLdb.connect(host, user, pw, charset='utf8')
# 创建游标,通过连接与数据通信
cursor = db.cursor()
# 执行sql语句
cursor.execute('show databases')
rows = cursor.fetchall()
for row in rows:
tmp = "%2s" % row
# 判断数据库是否存在
if name == tmp:
cursor.execute('drop database if exists ' + name)
cursor.execute('create database if not exists ' + name)
# 提交到数据库执行
db.commit()
except MySQLdb.Error, e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
finally:
# 关闭数据库连接
db.close()


cre_db(db_host, db_user, db_pw)

posted @ 2017-05-11 10:02  titan5750  阅读(16486)  评论(1编辑  收藏  举报