jxddk
jxddk

Reputation: 636

Sanitized queries in pyodbc returns only the field name

When I query my SQL server with pyodbc, I get only the name of the field I requested (instead of the values itself).

import pyodbc

conn = pyodbc.connect(connection_string)
cursor = conn.cursor()
cursor.execute('SELECT ? FROM [Projects]', '[ProjectNo]')
for row in cursor.fetchall():
    print(row)

This prints the following:

('[ProjectNo]', )
('[ProjectNo]', )
('[ProjectNo]', )
('[ProjectNo]', )
('[ProjectNo]', )
('[ProjectNo]', )
('[ProjectNo]', )
('[ProjectNo]', )
('[ProjectNo]', )

The number of lines is equal to the number of rows in the Projects table. I have the same issue when the second argument in cursor.execute is "[ProjectNo]", "ProjectNo", or even "blahblahblahblah"; each row only gives the requested field's name.

I do not have this problem if I use only one argument in cursor.execute:

cursor.execute('SELECT [ProjectNo] FROM [Projects]')

This will return what I expect it to.

What am I missing here?

Upvotes: 1

Views: 230

Answers (2)

jxddk
jxddk

Reputation: 636

As Serg answered in a comment:

Column names can't be a variable parameter in a constructed query/statement. Only values can be a parameter.

Upvotes: 0

Thangadurai.B
Thangadurai.B

Reputation: 561

You can use like this,

import pyodbc

conn = pyodbc.connect(connection_string)
cursor = conn.cursor()
cursor.execute('SELECT {} FROM [Projects]".format('[ProjectNo]'))
for row in cursor.fetchall():
    print(row)

Upvotes: 1

Related Questions