sql server - How to make dynamic updates to the database using a list in python -


if year in year:   #print 'executing'   rows in range(1,sheet.nrows):       records = []       fip = str(sheet.cell(rows, 1).value)       cols in range(9,sheet.ncols):           records.append(str(sheet.cell(rows,cols).value))       cur.execute("update " + str(table_name) + " set " + (str(variables[0]) + "= \'{0}\', ".format(records[0])                   + str(variables[1]) + " = \'{0}\', ".format(records[1])                   + str(variables[2]) + " = \'{0}\', ".format(records[2])                   + str(variables[3]) + " = \'{0}\', ".format(records[3])                   + str(variables[4]) + " = \'{0}\',".format(records[4])                   + str(variables[5]) + " = \'{0}\', ".format(records[5])                   + str(variables[6]) + " = \'{0}\' ".format(records[6])+                                         "where data_year='2010'and fips='{0}'".format(fip))) 

the above code updating 7 columns names stored in list 'variables'. want make dynamic if number of elements(columns) in list 'variables' increased, should update columns , not 7.
tried doing using code:

if year in year:   #print 'executing'   rows in range(1,sheet.nrows):       records = []       fip = str(sheet.cell(rows, 1).value)       cols in range(9,sheet.ncols):           records.append(str(sheet.cell(rows,cols).value))       x in range(0,len(variables)):           #print x           cur.execute("update " + str(table_name) + " set " + (str(variables[x])) + "= \'{0}\', ".format(records[x])                                         + "where data_year='2010' , fips='{0}'".format(fip)) 

but getting error:
pypyodbc.programmingerror: (u'42000', u"[42000] [microsoft][odbc sql server driver][sql server]incorrect syntax near keyword 'where'.")

it great if can me figure out what's wrong code , whether there alternate way of doing trying do.

you find easier use parameter-substitution. see params, , note execute takes sequence argument. line starts like,

cur.execute(sql, records) 

if memory permits (it does), may find executemany performs better: call once array of records.

with in mind, dynamic part of question comes focus. construct parameterized query string iterate on cols. when that's done, should have matched set (in effect) of parameter placeholders , elements in records. tack on clause, append fip records, , execute.

hth.


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -