Pandas insert into SQL Server



我在一个数据帧中读取了一个包含5列的excel文件(使用Pandas(,并试图使用以下代码将其写入现有的空sql server表

for index, row in df.iterrows():
PRCcrsr.execute("Insert into table([Field1], [Field2], [Field3], [Field4], [Field5]) VALUES(?,?,?,?,?)"
, row['dfcolumn1'],row['dfcolumn2'], row['dfcolumn3'], row['dfcolumn4'], row['dfcolumn5'])

我收到以下错误消息:TypeError:execute((接受2到5个位置参数,但有7个被赋予

shape说我有5列,但当我把df打印到屏幕上时,它包括RowNumber。其中一列是city_state,其中包含一个逗号。这就是它认为我提供7个参数(5个实际列+行号+逗号问题(的原因吗?在写入SQL Server之前,有没有办法处理数据帧中的逗号和行索引列?如果shape说5列,为什么我会出现这个错误?

上面的代码指示有7个参数被传递给游标执行命令,并且只允许在2到5之间。我实际上传递了7个参数(Insert into、Values和row[dfcolumn1、2、3、4、5-7(

new tuple = [tuple(r) for r in df.values.tolist()]

然后我重写for循环如下:

for tuple in new_tuple: 
PRCcrsr.execute = Insert into table([Field1], [Field2], [Field3], [Field4], [Field5]) VALUES(?,?,?,?,?)", tuple)

这将字段作为元组传递,并正确插入

相关内容

最新更新