if year in Year:
#print 'executing'
for rows in range(1,sheet.nrows):
records = []
FIP = str(sheet.cell(rows, 1).value)
for 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)))
上面的代码正在更新其名称存储在“variables”列表中的7列。
我想使其动态化,这样如果列表“variables”中的元素(列)数量增加,它应该更新所有列,而不仅仅是7列。
我试着用这个代码:
if year in Year:
#print 'executing'
for rows in range(1,sheet.nrows):
records = []
FIP = str(sheet.cell(rows, 1).value)
for cols in range(9,sheet.ncols):
records.append(str(sheet.cell(rows,cols).value))
for 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' AND FIPS='{0}'".format(FIP))
但我得到了一个错误:pypyodbc.ProgrammingError: (u'42000', u"[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'WHERE'.")
如果有人能帮我找出我的代码出了什么问题,以及是否有其他方法来做我正在尝试做的事情,那就太好了
您会发现使用参数替换更容易。请参见params,并注意execute采用序列参数。然后那条线开始看起来像
如果内存允许(它可能允许),您可能会发现executemany的性能更好:用一个记录数组调用它一次
有鉴于此,您问题的动态部分就成为焦点。在
cols
上迭代时构造参数化查询字符串。完成后,records
中应该有一组匹配的参数占位符和元素(实际上)。然后附加WHERE子句,将FIP附加到记录,然后执行嗯
相关问题 更多 >
编程相关推荐