2016-06-20 57 views
0

我知道這是一個熱門話題,但我搜索了各種答案,沒有看到我的問題的明確答案。我有一個函數用於將記錄插入到我的NDBC數據庫中,該數據庫給了我在標題中提到的錯誤。功能如下:Python MySQLdb TypeError(「並非所有在字符串格式化過程中轉換的參數」)

def insertStdMet(station,cursor,data): 
# This function takes in a station id, database cursor and an array of data. At present 
# it assumes the data is a pandas dataframe with the datetime value as the index 
# It may eventually be modified to be more flexible. With the parameters 
# passed in, it goes row by row and builds an INSERT INTO SQL statement 
# that assumes each row in the data array represents a new record to be 
# added. 
fields=list(data.columns) # if our table has been constructed properly, these column names should map to the fields in the data table 
# Building the SQL string 
strSQL1='REPLACE INTO std_met (station_id,date_time,' 
strSQL2='VALUES (' 
for f in fields: 
    strSQL1+=f+',' 
    strSQL2+='%s,' 
# trimming the last comma 
strSQL1=strSQL1[:-1] 
strSQL2=strSQL2[:-1] 
strSQL1+=") " + strSQL2 + ")" 
# Okay, now we have our SQL string. Now we need to build the list of tuples 
# that will be passed along with it to the .executemany() function. 
tuplist=[] 
for i in range(len(data)): 
    r=data.iloc[i][:] 
    datatup=(station,r.name) 
    for f in r: 
     datatup+=(f,) 
    tuplist.append(datatup) 
cursor.executemany(strSQL1,tuplist) 

當我們到達cursor.executemany()調用,STRSQL看起來是這樣的:

REPLACE INTO std_met (station_id,date_time,WDIR,WSPD,GST,WVHT,DPD,APD,MWD,PRES,ATMP,WTMP,DEWP,VIS) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' 

我使用%符號貫穿和我傳遞的列表元組(〜2315個元組)。每個傳遞的值都是字符串,日期時間或數字。我仍然沒有發現問題。任何人關心的任何見解都會受到真誠的讚賞。

謝謝!

回答

0

您還沒有給出您的SQL查詢值爲station_iddate_time,所以當它解包您的參數時,有兩個缺失。

我懷疑你想要的最終調用是這樣的:

REPLACE INTO std_met 
(station_id,date_time,WDIR,WSPD,GST,WVHT,DPD,APD,MWD, 
PRES,ATMP,WTMP,DEWP,VIS) VALUES (%s, %s, %s,%s,%s,%s, 
            %s,%s,%s,%s,%s,%s,%s,%s)' 

注意兩個額外%s。它看起來像你的元組已經包含station_id和date_time的值,所以你可以嘗試這個改變:

strSQL1='REPLACE INTO std_met (station_id,date_time,' 
strSQL2='VALUES (%s, %s, ' 
+0

當然這是愚蠢的。謝謝!現在它工作得很好! – RyanM

相關問題