【问题标题】:Python MySQLdb TypeError("not all arguments converted during string formatting")Python MySQLdb TypeError(“字符串格式化期间并非所有参数都转换”)
【发布时间】:2016-06-20 00:34:16
【问题描述】:

我知道这是一个热门话题,但我搜索了各种答案,但没有看到我的问题的明确答案。我有一个函数,我想用它来将记录插入到我的 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 个元组)。传递的每个值都是字符串、日期时间或数字。我仍然没有发现问题。我们真诚地感谢任何人愿意传递的任何见解。

谢谢!

【问题讨论】:

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


    【解决方案1】:

    您尚未为 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, '
    

    【讨论】:

    • 当然是那么傻。谢谢!现在效果很好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    相关资源
    最近更新 更多