python - Being that string substitution is frowned upon with forming SQL queries, how do you assign the table name dynamically? -
pretty new sqlite3, bear me here..
i'd have function can pass table name, , values update.
i started this:
def add_to_table(table_name, string): cursor.execute('insert {table} values ({var})' .format( table=table_name, var=string) )
which works a-ok, further reading sqlite3 suggested terribly insecure way go things. however, using ?
syntax, i'm unable pass in name specify variable.
i tried adding in ?
in place of table, throws syntax error.
cursor.execute('insert ? values (?)', ('mytable','"jello, world!"')) >> >sqlite3.operationalerror: near "?": syntax error
can table
in sql statement passed in safely , dynamically?
its not dynamic string substitution per-se thats problem. dynamic string substitution user-supplied string thats big problem because opens sql-injection attacks. if absolutely 100% sure tablename safe string control splicing sql query safe.
if some_condition(): table_name = 'table_a' else: table_name = 'table_b' cursor.execute('insert '+ table_name + 'values (?)', values)
that said, using dynamic sql code smell should double check see if can find simpler alternative without dynamically generated sql strings. additionally, if want dynamic sql sqlalchemy might useful guarantee sql generate formed.
Comments
Post a Comment