Question

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.

My SQL file contain this code -

select @@version;

GO

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()

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.

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

Was it helpful?

Solution

try this (add 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 ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top