简体   繁体   English

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

[英]Not able to execute sql command through a session created using POPEN in python

I'm trying to connect to SQL server using the below code I'm getting error invalid argument. 我正在尝试使用以下代码连接到SQL Server,但出现错误无效参数。 I'm trying to read from a sql file and the run the query on the session created by popen using sqlcmd. 我正在尝试从sql文件中读取内容,并使用sqlcmd在popen创建的会话上运行查询。

My SQL file contain this code - 我的SQL文件包含以下代码-

select @@version;

GO

this is my python code to make connection and run the command. 这是我建立连接并运行命令的python代码。 I'm getting "[Errno 22] Invalid argument" 我收到“ [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()

How can i degug this kind of situation. 我如何应对这种情况。 I'm pretty much novice to sql hence i'm not sure that this is the problem with my code or the way stdin works. 我是sql的新手,因此我不确定这是我的代码还是stdin工作方式的问题。

I'm able to run command using the sqlcmd utility on command prompt. 我可以在命令提示符下使用sqlcmd实用程序运行命令。 I'm using the sqlcmd for sql 2005 我正在将sqlcmd用于sql 2005

try this (add shell=True ): 试试这个(添加shell = True ):

session = Popen(connection_string, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)

or you can you can add explicit path of sqlcmd.exe to your string ... 或者您可以将sqlcmd.exe的显式路径添加到您的字符串中...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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