Python execute sql query using sqlcmd

时间:2016-11-12 05:56:12

标签: python sql sql-server sqlcmd

Hi I want to execute query using sqlcmd so I am calling it using subprocess.call() . This process sometimes its working but in loop it does not work. It only the execute the last argument. Please help below is the sample code I am trying-

import subprocess
host = 'hostname'
db = 'SQLTest'
sqlcmd = "C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE"
query = "INSERT INTO [dbo].[Test](type,ident,lat,long,y_proj,x_proj,new_seg,display,color,altitude,depth,temp,time,model,filename,ltime) VALUES ('TRACK','ACTIVE LOG','40.79015493','-77.85914183','4627311.94501541','1779470.5827101','False','False','255','351.979858398438','0','0','2008/06/11-14:33:33','eTrex Venture','','2008/06/11 09:33:33')"
for x in range (0,5):
    subprocess.call([sqlcmd,'-S' ,host, '-d', db, '-Q', query])

Or is there any other method. I even tried pymysql module. But it shows authentication error.

2 个答案:

答案 0 :(得分:0)

这是一个非常有创意的解决方案!

当你说“在循环中它不起作用”时,你能告诉我们发生了什么吗?有错误信息吗?它是否运行,但表中没有插入数据?你能让它在循环之外正常工作吗?

我注意到的第一件事是

sqlcmd = "c:\program files\...."

您可能希望通过在引号前放一个“r”来使其成为原始字符串,如下所示:

sqlcmd = r"c:\program files\...."

这将阻止Python尝试将反斜杠解释为特殊字符。

看起来你正试图与SQL Server交谈,所以pymysql不会有帮助(那就是与MySQL服务器交谈)。我建议将pyodbc或pymssql作为替代方案。

答案 1 :(得分:0)

我收到了错误。它与我传递的查询有关。查询是从文本文件中读取的。所以它除了最后一个查询外都有空格。对于单一测试,我使用的是最后一个查询。在确定它有效之后。