python执行mysql source命令

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



评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值