Home >Database >Mysql Tutorial >python执行mysql source命令
近来在看python,于是,将某个shell实现过的功能用python实现下
1 python 操作mysql 需要有 MySQLdb 这个库的支持,一般需要单独安装
2 MySQLdb库只能执行sql语句,对于sql文件执行,比较麻烦,所以用了subprocess库的方法Popen
相关mysql视频教程推荐:《mysql教程》
import MySQLdb from subprocess import Popen,PIPE sqlta = "/usr/local/webserver/scripts/ta.sql" sqlclita = "/usr/local/webserver/scripts/clita.sql" Platform = raw_input('Please Enter Platform:') Server = raw_input('Please Enter Server:') LogTa = "LogTa_"+Platform+"_"+Server LogCliTa = "LogCliTa_"+Platform+"_"+Server host = "192.168.0.1" usr = "admin" passwd = "admin8SQBL" port = 3303 try: conn = MySQLdb.connect(host=host,user=usr,passwd=passwd,port=port) cur = conn.cursor() cur.execute('create database IF NOT EXISTS '+LogTa) cur.execute('create database IF NOT EXISTS '+LogCliTa) cur.close() conn.close() except MySQLdb.Error,e: print "Mysql Error %d: %s" % (e.args[0], e.args[1]) process = Popen('/usr/local/webserver/mysql/bin/mysql -h%s -P%s -u%s -p%s %s' %(host, port, usr, passwd, LogTa), stdout=PIPE, stdin=PIPE, shell=True) output = process.communicate('source '+sqlta) process = Popen('/usr/local/webserver/mysql/bin/mysql -h%s -P%s -u%s -p%s %s' %(host, port, usr, passwd, LogCliTa), stdout=PIPE, stdin=PIPE, shell=True) output = process.communicate('source '+sqlclita)
相当于用MySQLdb库创建了数据库,然后用Popen,进行sql文件的执行操作。Popen()函数相当于用shell来执行..