违反UNIQUE KEY约束-熊猫to_sql Python SQLAlchemy

时间:2019-03-19 13:57:37

标签: python sql-server pandas sqlalchemy

我正在尝试使用Pandas的to_sql方法将数据帧输入到SQL Server数据库中,并且出现错误:

  

“ 23000”,“ [23000] [Microsoft] [SQL Server Native Client 11.0] [SQL   服务器]违反UNIQUE KEY约束...无法插入重复项   键入对象

其他人在这里发布了类似的问题: Pandas to_sql 'append' to an existing table causes Python crash

但是,他的解决方案基本上是他需要删除主键重复项,因为他不止一次提交主键。我什至不尝试提交主键,我希望SQL Server分配它。这是我调用的方法:

df.to_sql('table_name', engine, if_exists='append', index=False, chunksize=1000)

我知道引擎可以连接数据库,因为如果我使用read_sql方法,它可以很好地从数据库中返回数据。我只是无法写入数据库,显然我什至在不尝试触摸主键的情况下仍在重用主键。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

I think I figured it out. The database was set up as not to allow the same name and address 1 field, and my data had some duplicates for address 1 but differences in address 2. Need to make some database changes and then try again. I'm going to leave my question up to help others who may encounter similar issues.