Being that string substitution is frowned upon with forming SQL queries, how do you assign the table name dynamically?

Its not the dynamic string substitution per-se thats the problem. Its dynamic string substitution with an user-supplied string thats the big problem because that opens you to SQL-injection attacks. If you are absolutely 100% sure that the tablename is a safe string that you control then splicing it into the SQL query will be safe.

if some_condition():
   table_name="TABLE_A"
else:
   table_name="TABLE_B"

cursor.execute('INSERT INTO '+ table_name + 'VALUES (?)', values)

That said, using dynamic SQL like that is certainly a code smell so you should double check to see if you can find a simpler alternative without the dynamically generated SQL strings. Additionally, if you really want dynamic SQL then something like SQLAlchemy might be useful to guarantee that the SQL you generate is well formed.

Leave a Comment