繁体   English   中英

无法通过在python中使用POPEN创建的会话执行sql命令

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM