Skip to content
Advertisement

SQL How to SELECT python variable in SQL

Tried something like this cur.execute(‘SELECT ? FROM translations WHERE imagename = ? ‘, (target, filename,))

but it just returned [(‘de’,), (‘de’,), (‘de’,), (‘de’,), (‘de’,), (‘de’,)]

being target = ‘de’

Advertisement

Answer

You cannot use ? for database object names, such as table and column names. Allowing this would represent a big security risk. One workaround here would be to just maintain separate statements for each logic flow, e.g.

if target == "col1":
    cur.execute('SELECT col1 FROM translations WHERE imagename = ?', (filename,))
elif target == "col2":
    cur.execute('SELECT col2 FROM translations WHERE imagename = ?', (filename,))
else:
    cur.execute('SELECT col3 FROM translations WHERE imagename = ?', (filename,))
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement