我的要求是我需要启动一个sqlcmd进程,然后将sql语句提供给该进程并检索该方案中生成的输出。在你们建议我使用sql库运行sqlcmd之前,让我告诉你我不能这样做,我只要求使用sqlcmd来实现它。
这是我当前的代码
from subprocess import Popen, PIPE
def ms_sql_session():
IP = "xxxx"
port = '1433'
username = 'sa'
password = 'abc'
connString = 'sqlcmd -S tcp:%s,%s -dmaster -U%s -P%s ' %(IP, port, username, password)
try:
session = Popen(connString, stdin=PIPE, stdout=PIPE, stderr=PIPE)
str_cmd = '''select @@version;
go
'''
session.stdin.write(str_cmd)
stdout, stderr = session.communicate()
print stdout
print stderr
str_cmd = '''select @@version;
go
'''
session.stdin.write(str_cmd)
#stdout, stderr = session.communicate()
print stdout
print stderr
str_cmd = '''select @@version;
go'''
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()
我正在尝试执行3语句并检索o / p,但我在第二次stdin.write操作中得到异常
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Microsoft SQL Server 2005 - 9.00.5000.00 (Intel X86)
Dec 10 2010 10:56:29
Copyright (c) 1988-2005 Microsoft Corporation
Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 2)
(1 rows affected)
I/O operation on closed file
这是我代码的输出。
答案 0 :(得分:0)
为什么要使用系统cmd呢?我建议使用SQL库...