mysql - Python MySQLdb variables as table names -


i have syntax error in python which stops mysqldb inserting database. sql insert below.

cursor.execute("insert %s (description, url) values (%s, %s);", (table_name.encode("utf-8"), key.encode("utf-8"), data[key].encode("utf-8")))  

i following error in stack trace.

_mysql_exceptions.programmingerror: (1064, "you have error in  sql syntax; check manual corresponds mariadb server  version right syntax use near ''four' (description, url) values ('', 'http://imgur.com/a/v8sdh')' @ line 1") 

i appreciate assistance cannot figure out.

edit:

fixed following line:

cursor.execute("insert " + table_name + " (description, url) values (%s, %s);", (key.encode("utf-8"), data[key].encode("utf-8"))) 

not sophisticated, hope use jumping off point.

it looks sql statement:

cursor.execute("insert %s (description, url) values (%s, %s);", (table_name.encode("utf-8"), key.encode("utf-8"), data[key].encode("utf-8"))) 

iirc, name of table not able parameterized (because gets quoted improperly). you'll need inject string other way (preferably safely -- checking table name requested matches whitelisted set of table names)... e.g.:

_table_name_whitelist = frozenset(['four'])  ... if table_name not in _table_name_whitelist:     raise exception('probably better define specific exception this...')  cursor.execute("insert {table_name} (description, url) values (%s, %s);".format(table_name=table_name),     (table_name.encode("utf-8"),      key.encode("utf-8"),      data[key].encode("utf-8"))) 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -