python中用os.system+sqlcmd执行sql脚本

1、系统环境python

win7+python2.7mysql

2、python代码sql

import os
os.system("sqlcmd -S localhost -U sa -P 123456 -d TRAINING -i \"d:\\sql\\tmp.txt\"")

sqlcmd命令参数说明:shell

-S:表示数据库服务器地址,如localhost数据库

-U:用户名,如sawindows

-P: 密码,如123456bash

-d:数据库名,如TRAINING服务器

-i:文件路径,如文件存放在d:\sql\tmp.txt, 须要写成这样 \"d:\\sql\\tmp.txt\"python2.7

路径书写须要注意下。路径用双引号"file_path",外面已经有双引号了,须要转义。由于是在windows系统,路径用反斜杠,也须要转义下。spa

其余的参数,能够经过windows系统中的cmd命令查看:

sqlcmd /?

sqlcmd参数

 

 

 

 

 

 

 

 

 

 

 

3、其余说明

(1)os.system:python中能够经过 os.system(cmd) 来执行命令,其效果就像在cmd中执行同样。另外,在python中调用shell的方法不少,如:

os.system(command)
os.popen(command,mode)
commands.getstatusoutput(command)
subprocess.call(["some_command","some_argument","another_argument_or_path"])
subprocess.Popen(command,shell=True)

关于python中如何调用shell的其余方法,请参考这篇文章:

http://blog.csdn.net/gray13/article/details/7044453

(2)sqlcmd:在使用的时候会碰到这样的问题,在windows的cmd命令中输入sqlcmd,而后输入命令.....而后.....尼玛....它没有任何反应。就像这样:

sqlcmd没反应

 

 

 

其实很简单,写完语句后,再输入go就能执行了

go

(3)逐句执行sql

有的时候为了控制sql的执行,须要逐句执行,这个时候就不能用上面的办法。须要换个办法,参考这个:

"""
需求描述:
    要在服务器上指执行sql
    为了避免影响线上用户正常使用, 且执行10000行暂停10秒。
    而后用python
    写了这样一个文件
    文件存放位置: / root / sql /
    文件名:2 3 4 5 6.....
    这样作是为了省事
    用range(2, 24)
    其实能够写成读取目录文件:os.listdir("/root/sql/")
"""

import os
import time
import math
##读取文件
for i in range(2, 24):
    ##拼接文件完整路径
    filename = "/root/sql/" + str(i)
    file = open(filename, 'r')
    ##计数器(控制暂停)
    count = 0
    for line in file:
        count += 1
        if line:
            lines = line[:line.find(';')]
            cmd = "mysql -u root -pxxxx dbname -e " + '"' + lines + '"'
            print cmd
            os.system(cmd)
            print count
            if count == 10000:
                time.sleep(10)
                count = 0
    file.close()

该方法来自:http://2643235.blog.51cto.com/2633235/1406728

相关文章
相关标签/搜索