"no such column" error when trying to update

Question:

I am trying to replace a string with an id:

import sqlite3

TABLES = ['table1', 'table2', ...]
PAR_TYPES_STRINGS = ['foo', 'bar', ...]
PAR_TYPES_ID = [1, 2, ...]

def upateTable(table, parTypeId, parTypeString):
  return f"UPDATE {table} SET par_type = {parTypeId} WHERE par_type = {parTypeString};"

conn = sqlite3.connect('existing_db.db')
cursor = conn.cursor()

for table in TABLES:
  for index, parTypeString in enumerate(PAR_TYPES_STRINGS):
    parTypeId = PAR_TYPES_ID[index]
    cursor.execute(upateTable(table, parTypeId, parTypeString))
conn.commit()
cursor.close()

Returns:

sqlite3.OperationalError: no such column: foo

I am using par_type statically as a column name, comparing it to parTypeString (which has foo in it dynamically).

WHERE par_type = {parTypeString} < dynamically passed variable
      ^
      hardcoded column name

Yet, it says "no such column foo", which is the first element the for loop takes out of PAR_TYPES_STRINGS. Why is that?

Asked By: four-eyes

||

Answers:

In the function definition, you need to put {parTypeString} in quotes: '{parTypeString}', because you want to check where the hardcoded column matches that string. Otherwise the expression is interpreted to check equality between two columns, hence the error message.

Answered By: Arne
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.