2016-07-15 48 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。

相關問題