标签:cursor pytho row 数据通信 database creat mysqldb mysql odi
昨天用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)
标签:cursor pytho row 数据通信 database creat mysqldb mysql odi
原文地址:http://www.cnblogs.com/titan5750/p/6839503.html