Creating Insert Statement for MySQL in Python -
i trying construct insert statement built results of query. run query retrieves results 1 database , creates insert statement results , inserts different database.
the server queried returns fields in reply populated , can differ record record. destination database table has of possible fields available. why need construct insert statement on fly each record retrieved , why cannot use default list of fields have no control on ones populated in response.
here sample of code, send off request t&c isin , response name , value.
fields = [] data = [] gettcq = ("mdh:t&c|"+isin+"|name|value") mdh.execute(gettcq) tc = mdh.fetchall() values in tc: fields.append(values[0]) data.append(values[1]) insertq = ("insert sp_fields ("+fields+") values ('"+data+"')")
the problem fields part, mysql expecting following:
insert sp_fields (accrual_count,amount_outstanding_calc_date) values ('030/360','2014-11-10')
but getting following insertq:
insert sp_fields ('accrual_count','amount_outstanding_calc_date') values ('030/360','2014-11-10')
and mysql not ' ' around fields names.
how rid of these? looks 1st insertq statement works.
many in advance.
you use ','.join(fields)
create desired string (without quotes around each field).
then use parametrized sql , pass values second argument cursor.execute
:
insertq = ("insert sp_fields ({}) values ({})".format( ','.join(fields), ','.join(['%s']*len(dates))) cursor.execute(insertq, dates)
note correct placemarker use, e.g. %s
, depends on db adapter using. mysqldb uses %s
, oursql
uses ?
, instance.
Comments
Post a Comment