1

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?

joedeandev
  • 626
  • 1
  • 6
  • 15
  • You can't use parameters for the db objects (columns, tables..). Use it for values only. – Serg Oct 16 '19 at 12:22
  • @Serg Aha, of course. I remembered having this problem before, and that the answer was obvious. Thank you – joedeandev Oct 16 '19 at 12:23

2 Answers2

1

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)
Thangadurai.B
  • 561
  • 1
  • 3
  • 18
0

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.

joedeandev
  • 626
  • 1
  • 6
  • 15