0
votes

I'm getting an error at this statement:

cursor.execute("SELECT * FROM dbo.User")

Error:

pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near the keyword 'User'. (156) (SQLExecDirectW)")

The code is below. I'm assuming the connection is fine because nothing happens unless I execute the query? Am I doing something wrong?

SERVER = 'LAPTOP-1E7UL24T\SQLEXPRESS02'
DATABASE = 'PT'
DRIVER='{ODBC Driver 17 for SQL Server}'
DATABASE_CONNECTION=f'Driver={DRIVER};SERVER={SERVER};Database={DATABASE};Trusted_Connection=yes;'
print(DATABASE_CONNECTION)
cnxn=pyodbc.connect(DATABASE_CONNECTION)

cursor=cnxn.cursor()
cursor.execute("SELECT * FROM dbo.User")
1
Dale, Im just getting "syntax error near User"Rolando Riccio
cursor.execute("SELECT * FROM User") pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near the keyword 'User'. (156) (SQLExecDirectW)")Rolando Riccio

1 Answers

1
votes

User is a reserved word and needs to be escaped, commonly by using square brackets e.g.

SELECT * FROM dbo.[User]

But double quotes also work:

SELECT * FROM dbo."User"

Although it will make your life (and any developers who follow) a lot easier if you just avoid using reserved words.