无法通过在 python 中使用 POPEN 创建的会话执行 sql 命令 [英] Not able to execute sql command through a session created using POPEN in python

查看:69
本文介绍了无法通过在 python 中使用 POPEN 创建的会话执行 sql 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码连接到 SQL 服务器,但出现错误无效参数.我正在尝试从 sql 文件中读取数据,并使用 sqlcmd 在 popen 创建的会话上运行查询.

I'm trying to connect to SQL server using the below code I'm getting error invalid argument. I'm trying to read from a sql file and the run the query on the session created by popen using sqlcmd.

我的 SQL 文件包含此代码 -

My SQL file contain this code -

select @@version;

GO

这是我建立连接并运行命令的python代码.我收到[Errno 22] 无效参数"

this is my python code to make connection and run the command. I'm getting "[Errno 22] Invalid argument"

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 几乎是新手,因此我不确定这是我的代码的问题还是标准输入的工作方式.

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.

我可以在命令提示符下使用 sqlcmd 实用程序运行命令.我正在使用 sqlcmd for sql 2005

I'm able to run command using the sqlcmd utility on command prompt. I'm using the sqlcmd for sql 2005

推荐答案

试试这个(添加shell=True):

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

或者您可以将 sqlcmd.exe 的显式路径添加到您的字符串中...

or you can you can add explicit path of sqlcmd.exe to your string ...

这篇关于无法通过在 python 中使用 POPEN 创建的会话执行 sql 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆