【发布时间】: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