mysql - Python MySQLdb "INSERT INTO" Issue -
my code attempts iterate through dictionary, "dbmap", , execute mysql insert statements based on keys , values of dbmap:
for key in dbmap: try: cursor.execute("insert '%s' (id, additional_details) values (123, '%s')", (key, dbmap[key])) except unicodeencodeerror: pass
i following error when run above code:
_mysql_exceptions.programmingerror: (1064, "you have error in sql syntax; check manual corresponds mysql server version right syntax use near '''random_key'' (id, additional_details) values (123, 'random_value' @ line 1")
i don't see mysql syntax i'm violating, following following resources help:
http://www.mikusa.com/python-mysql-docs/query.html
http://www.w3schools.com/sql/sql_insert.asp
update:when try this:
for key in dbmap: try: cursor.execute("insert {} (id, additional_details) values (123, '{}')".format(key, dbmap[key])) except unicodeencodeerror: pass
i different error:
_mysql_exceptions.operationalerror: (1054, "unknown column 'id' in 'field list'")
update 2:
for key in dbmap: try: query = "insert `%s` (id, additional_details) values(123, %%s)" % key cursor.execute(query, dbmap[key]) except unicodeencodeerror: pass
got new error: typeerror: not arguments converted during string formatting
any assistance in helping me figure out what's going wrong appreciated
when using python's mysql library, think don't want use '
around variables. believe make %s
interpreted literally, instead of having them substituted. it's been awhile, since i've used method, though, off-base. try this:
try: cursor.execute("insert %s (id, additional_details) values (123, %s)", (key, dbmap[key]))
python substitution you.
also, considering using abstraction prevent sql injection. check out - this post - 1 of so's frequently-viewed.
separately, since i'm looking closer @ python line, , actual error, think line doesn't think does.
for key in dbmap
produce values of dbmap
, not key values - when call dbmap[key]
, since key
isn't index, it's getting error. might mean you're not getting right table you're looking insert key
. food thought. try:
for idx, value in enumerate(dbmap): cursor.execute("insert %s (id, additional_details) values (123, %s)", (idx, dbmap[idx]))
this allow access key index (idx
) , mapdb
value.
Comments
Post a Comment