首页 >数据库 >mysql教程 >python执行mysql source命令

python执行mysql source命令

PHPz
PHPz原创
2016-06-06 09:41:293863浏览

近来在看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来执行..

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn