Home:ALL Converter>Creating Insert Statement for MySQL in Python

Creating Insert Statement for MySQL in Python

Ask Time:2014-11-19T23:21:41         Author:Peter Louw

Json Formatter

I am trying to construct an insert statement that is built from the results of a query. I run a query that retrieves results from one database and then creates an insert statement from the results and inserts that into a different database.

The server that is initially queried only returns those fields in the reply which are populated and this can differ from record to record. The destination database table has all of the possible fields available. This is why I need to construct the insert statement on the fly for each record that is retrieved and why I cannot use a default list of fields as I have no control over which ones will be populated in the response.

Here is a sample of the code, I send off a request for the T&C for an isin and the response is a name and value.

fields = []
data = []
getTCQ = ("MDH:T&C|"+isin+"|NAME|VALUE")
mdh.execute(getTCQ)
TC = mdh.fetchall()
for values in TC:
    fields.append(values[0])
    data.append(values[1])
 insertQ = ("INSERT INTO sp_fields ("+fields+") VALUES ('"+data+"')")

The problem is with the fields part, mysql is expecting the following:

INSERT INTO sp_fields (ACCRUAL_COUNT,AMOUNT_OUTSTANDING_CALC_DATE) VALUES ('030/360','2014-11-10')

But I am getting the following for insertQ:

INSERT INTO sp_fields ('ACCRUAL_COUNT','AMOUNT_OUTSTANDING_CALC_DATE') VALUES ('030/360','2014-11-10')

and mysql does not like the ' ' around the fields names.

How do I get rid of these? so that it looks like the 1st insertQ statement that works.

many thanks in advance.

Author:Peter Louw,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/27020472/creating-insert-statement-for-mysql-in-python
yy