Python MySQLdb TypeError("并非在字符串格式化期间转换的所有参数")

时间:2016-06-20 00:34:16

标签: python python-3.x mysql-python

我知道这是一个热门话题,但我搜索了各种答案,并没有看到我的问题的明确答案。我有一个函数,我想用来将记录插入我的NDBC数据库,这给我标题中提到的错误。功能如下:

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元组)。传递的每个值都是字符串,日期时间或数字。我还没有找到问题。任何人关心传递的见解都将深表感谢。

谢谢!

1 个答案:

答案 0 :(得分:0)

您还没有为station_iddate_time提供SQL查询的值,所以当它解压缩您的参数时,有两个缺失。

我怀疑你希望最后的通话是这样的:

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, '