2016-07-15 201 views
0
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))) 

以上代码正在更新名称存储在列表'变量'中的7列。 我想让它动态的,所以,如果列表中的“变量”元素(列)的数量增加时,应该更新所有列,而不仅仅是7
我想这样做,使用此代码:如何使用python中的列表动态更新数据库

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'.")

这将是巨大的,如果有人可以帮助我弄清楚什么是错我的代码及是否有在做什么,我试图做的另一种方法。

回答

0

您会发现使用参数替换更容易。请参阅params,并注意执行接受序列参数。然后,该行开始看起来像,

cur.execute(sql, records) 

如果内存许可证(它可能做),你可能会发现executemany更好地执行:你的记录数组调用它一次。

考虑到这一点,你的问题的动态部分成为焦点。在迭代cols时构建参数化查询字符串。完成后,您应该在records中拥有一组匹配的参数占位符和元素(实际上)。然后添加WHERE子句,将FIP附加到记录,然后执行。

HTH。

相关问题