[FIXED] Python MySQLdb "INSERT INTO" Issue

Issue

My code attempts to iterate through dictionary, "dbMap", and execute MySQL INSERT INTO statements based on the keys and values of dbMAP:

for key in dbMap:
    try:
        cursor.execute("INSERT INTO '%s' (id, additional_details) VALUES (123, '%s')", (key, dbMap[key]))
    except UnicodeEncodeError:
        pass

I get the following error when I run the above code:

_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''random_key'' (id, additional_details) VALUES (123, 'random_value' at line 1")

I don't see what MySQL syntax I'm violating, I am following the following resources for help:

http://www.mikusa.com/python-mysql-docs/query.html

http://www.w3schools.com/sql/sql_insert.asp

UPDATE:When I try this:

for key in dbMap:
    try:
        cursor.execute("INSERT INTO {} (id, additional_details) VALUES (123, '{}')".format(key, dbMap[key]))
    except UnicodeEncodeError:
        pass

I get a different error:

_mysql_exceptions.OperationalError: (1054, "Unknown column 'id' in 'field list'")

UPDATE 2:

for key in dbMap:
    try:
        query = "INSERT INTO `%s` (id, additional_details) VALUES(123, %%s)" % key
        cursor.execute(query, dbMap[key])
    except UnicodeEncodeError:
        pass

Got a new error: TypeError: not all arguments converted during string formatting

Any assistance in helping me figure out what's going wrong is much appreciated


Solution

The mysqldb library only lets you substitute values, not tables:

Python and MySQLdb: substitution of table resulting in syntax error



Answered By - Blythe Simmons
Answer Checked By - Gilberto Lyons (sql.easybugfix Admin)

Related Posts

Post a Comment