Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pyodbc Incorrect syntax near '-'. (102)

Tags:

python

sql

pyodbc

I am trying to select all data from table that contains "-" dash symbol, and i get error

    cursor.execute(qStr)
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near '-'. (102) (SQLExecDirectW)")

This is code:

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=192.168.2.100\name;DATABASE=base;UID=user;PWD=pass')

try:
    cursor = cnxn.cursor()
except e:
    if e.__class__ == pyodbc.ProgrammingError:        
        conn == reinit()
        cursor = conn.cursor()

def checkIfEmpty (tableName):
    qStr = 'SELECT * FROM [' + tableName + ']'
    print(qStr)
    cursor.execute(qStr)
    asd=cursor.fetchone()
    if asd==None:
        return True
    else:
        return False

It prints out correct SQL statement SELECT * FROM [Table-Name] and in Microsoft SQL Management Studio this query works just fine with copy paste, but it wont work from python console

Same thing is with:qStr = 'SELECT * FROM "' + tableName + '"

Why is this happening, how can i get around it?

like image 542
Energizem Avatar asked Aug 01 '17 10:08

Energizem


People also ask

What driver do I use for Pyodbc?

pyODBC uses the Microsoft ODBC driver for SQL Server.

What is Pyodbc in Python?

pyodbc is an open source Python module that provides access to ODBC databases. pyodbc implements the Python DB API 2.0 specification. The Python DB API defines a database-neutral interface to data stored in relational databases.

What is incorrect syntax near in SQL?

When executing a query in SQL and the editor throws back this error: Incorrect syntax near …'' That typically means you have used the wrong syntax for the query. This happens mostly when someone switched from one relational database to another relational database, from MySQL to MS SQL Server for example.


1 Answers

Try using Brackets wherever there is dash.

qStr = "SELECT * FROM [{}]".format(tableName)
like image 145
Rahul Avatar answered Sep 28 '22 19:09

Rahul