[FIXED] Error Passing Variable to SQL Server Query Python

Issue

            cursor.execute(""" if exists ( SELECT * from Alert where alert = ? and date = ? and devicename = ? )
                BEGIN
                update Alert set alert = ? where alert = ? and date = ? and devicename = ?
                END
                ELSE
                BEGIN
                INSERT INTO Alert (alert,date,devicename) VALUES (?, ?, ?) """, row[1], row[0], filename[:-4],
                           row[1], row[1], row[0], filename[:-4], row[1], row[0], filename[:-4])
            cursor.commit()

The above code is my sql query for SQLServer. It works if I replace the ? with value but if I do it this way, I receive error. Need help. I am using pyodbc library btw.

cursor.execute(""" if exists ( SELECT * from Alert where alert = ? and date = ? and devicename = ? ) pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near ')'. (102) (SQLExecDirectW); [42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Statement(s) could not be prepared. (8180)")


Solution

You should be passing a tuple of 10 parameters as the second parameter to cursor#execute():

sql =  """IF EXISTS (SELECT 1 FROM Alert WHERE alert = ? AND date = ? AND devicename = ?)
          BEGIN
              UPDATE Alert SET alert = ? WHERE alert = ? AND date = ? AND devicename = ?
          END
          ELSE
          BEGIN
              INSERT INTO Alert (alert, date, devicename) VALUES (?, ?, ?)
          END """
params = (row[1], row[0], filename[:-4], row[1], row[1], row[0], filename[:-4],
          row[1], row[0], filename[:-4])
cursor.execute(sql, params)


Answered By - Tim Biegeleisen
Answer Checked By - Marie Seifert (sql.easybugfix Admin)

Related Posts

Post a Comment