Home:ALL Converter>MySQL Dynamic Query Statement in Python with Dictionary

MySQL Dynamic Query Statement in Python with Dictionary

Ask Time:2013-04-27T23:39:35         Author:lawless

Json Formatter

Very similar to this question MySQL Dynamic Query Statement in Python

However what I am looking to do instead of two lists is to use a dictionary

Let's say i have this dictionary

instance_insert = {
#    sql column      variable value
    'instance_id'   : 'instnace.id',
    'customer_id'   : 'customer.id',
    'os'            : 'instance.platform',
}

And I want to populate a mysql database with an insert statement using sql column as the sql column name and the variable name as the variable that will hold the value that is to be inserted into the mysql table.

Kind of lost because I don't understand exactly what this statement does, but was pulled from the question that I posted where he was using two lists to do what he wanted.

sql = "INSERT INTO instance_info_test VALUES (%s);" % ', '.join('?' for _ in instance_insert)
cur.execute (sql, instance_insert)

Also I would like it to be dynamic in the sense that I can add/remove columns to the dictionary

Author:lawless,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/16253938/mysql-dynamic-query-statement-in-python-with-dictionary
yy