[英]Not able to execute sql command through a session created using POPEN in python
我正在嘗試使用以下代碼連接到SQL Server,但出現錯誤無效參數。 我正在嘗試從sql文件中讀取內容,並使用sqlcmd在popen創建的會話上運行查詢。
我的SQL文件包含以下代碼-
select @@version;
GO
這是我建立連接並運行命令的python代碼。 我收到“ [Errno 22]無效的參數”
import os
import subprocess
from subprocess import Popen, PIPE, STDOUT
def ms_sql_session():
ip_addr = "xxx.xxx.xxx.xxx,1433"
user = 'sa'
password = 'password'
connection_string = 'sqlcmd -S %s -U %s -P %s' %(ip_addr, user, password)
try:
session = Popen(connection_string, stdin=PIPE, stdout=PIPE, stderr=PIPE)
f = open('abc.sql','r')
str_cmd = f.read()
session.stdin.write(str_cmd)
stdout, stderr = session.communicate()
print stdout
print stderr
return True
except Exception, e:
print str(e)
return False
ms_sql_session()
我如何應對這種情況。 我是sql的新手,因此我不確定這是我的代碼還是stdin工作方式的問題。
我可以在命令提示符下使用sqlcmd實用程序運行命令。 我正在將sqlcmd用於sql 2005
試試這個(添加shell = True ):
session = Popen(connection_string, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
或者您可以將sqlcmd.exe的顯式路徑添加到您的字符串中...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.