python执行mysql source命令

来源:互联网 发布:淘宝不能打卡了 编辑:程序博客网 时间:2024/05/16 07:16

近来在看python,于是,将某个shell实现过的功能用python实现下

1 python 操作mysql 需要有 MySQLdb 这个库的支持,一般需要单独安装

2 MySQLdb库只能执行sql语句,对于sql文件执行,比较麻烦,所以用了subprocess库的方法Popen


  1. import MySQLdb  
  2. from subprocess import Popen,PIPE  
  3. sqlta = "/usr/local/webserver/scripts/ta.sql"  
  4. sqlclita = "/usr/local/webserver/scripts/clita.sql"  
  5. Platform = raw_input('Please Enter Platform:')  
  6. Server = raw_input('Please Enter Server:')  
  7. LogTa = "LogTa_"+Platform+"_"+Server  
  8. LogCliTa = "LogCliTa_"+Platform+"_"+Server  
  9. host = "192.168.0.1"  
  10. usr = "admin"  
  11. passwd = "admin8SQBL"  
  12. port = 3303  
  13. try:  
  14.         conn = MySQLdb.connect(host=host,user=usr,passwd=passwd,port=port)  
  15.         cur = conn.cursor()  
  16.         cur.execute('create database IF NOT EXISTS '+LogTa)  
  17.         cur.execute('create database IF NOT EXISTS '+LogCliTa)  
  18.         cur.close()  
  19.         conn.close()  
  20. except MySQLdb.Error,e:  
  21.         print "Mysql Error %d: %s" % (e.args[0], e.args[1])  
  22. 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)  
  23. output = process.communicate('source '+sqlta)  
  24.   
  25. 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)  
  26. output = process.communicate('source '+sqlclita)  

   相当于用MySQLdb库创建了数据库,然后用Popen,进行sql文件的执行操作。Popen()函数相当于用shell来执行..



0 0