SmartError
SmartError

Reputation: 13

Python - PyODBC - multiple queries with loop

I'm facing problems with sending multiple queries to SQL Server 2012 through pyODBC in Python. I have a DataFrame with queries and I want to use it to query DB. Something like this:

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=mySERVER;DATABASE=myDB;UID=myUID;PWD=myPSWD')
cursor = cnxn.cursor()
cursor2 = cnxn.cursor()

for i in range(len(myDataFrame.Column_w_Queries)):
    query = '"' + myDataFrame.Column_w_Queries[i] + '"'
    cursor.execute(query)
    one = cursor.fetchone()
    print(one)

query in this example is "select * from [DB].[schema].[table1]" (including quotes).

Problem is, that when I run cursor.execute(query) I got following error:

ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Could not find stored procedure 'select * from [DB].[schema].[table1]'. (2812) (SQLExecDirectW)")

What am I doing wrong?

Upvotes: 1

Views: 3385

Answers (1)

FlipperPA
FlipperPA

Reputation: 14361

You have to get rid of the surrounding double quotes. For example, open up SQL Server Management Studio, and try to run:

"select * from [DB].[schema].[table1]"

You'll get the error:

Msg 2812, Level 16, State 62, Line 1
Could not find stored procedure 'select * from [DB].[schema].[table1]'.

Now try:

select * from [DB].[schema].[table1]

...and it should work. Best of luck!

Upvotes: 1

Related Questions