gpt4 book ai didi

python - 如何使用 pyodbcexecutemany() 处理主键约束违规

转载 作者:行者123 更新时间:2023-12-01 01:16:23 26 4
gpt4 key购买 nike

我有一个脚本,可以使用 executemany() 在表中插入 DataFrame。

问题在于该表有一个ID作为主键,有时会出现插入具有相同ID的行的情况。

我想知道是否有一种简单的方法来处理这种异常并继续执行executemany()

我想到的替代方案是检查表中 DataFrame 的所有 ID,并在插入数据库之前删除它们......但我不知道这是否会表现出色...

我的代码:

params = (tuple(row) for _, row in df.iterrows())
sql = '''INSERT INTO stilingue.stalker_comments values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'''
start = time.time()
try:
self.cursor.executemany(sql, params)
self.conn.commit()
except Exception as e:
print(e)
self.conn.rollback()
print('Something went wrong...')
end = time.time()
print('Execution time: {0:.2f} seconds.'.format(end-start))

数据帧:

    channel followers   gender  hashtags    interactions    likes   location    mentions    name    page_comment    ... text    themes  uid user_image_url  user_url    username    verified    videoplays  business    rt_count
0 Inbox do Facebook 0 Não Definido 0 0 Midiam Mendes False ... Sacanagem isso né?? Poorq vocês dizeram que o ... 1995608377159933 https://storage.googleapis.com/usersstilingue/... False 0 Itaú 0
1 Inbox do Facebook 0 Não Definido 0 0 Midiam Mendes False ... Eu tenho provas , e posso processar vocês!! 1995608377159933 https://storage.googleapis.com/usersstilingue/... False 0 Itaú 0
2 Inbox do Facebook 0 Não Definido 0 0 Midiam Mendes False ... Isso é um absurdo 1995608377159933 https://storage.googleapis.com/usersstilingue/... False 0 Itaú 0

回溯:

('23000', "[23000] [Microsoft][ODBC SQL Server Driver][SQL Server]Violation of PRIMARY KEY constraint 'PK__stalker___DD37D91A4691B0F7'. Cannot insert duplicate key in object 'stilingue.stalker_comments'. The duplicate key value is (m__g64-pbys7OlEvp8xmfyktlNIHrUPQPiNrcKrPVOF_Lj84OJfN4WtAJ92lj7YnzAOQ1B7EDCJf85k_UcwB0-4Q). (2627) (SQLExecDirectW); [23000] [Microsoft][ODBC SQL Server Driver][SQL Server]The statement has been terminated. (3621)")

最佳答案

如果你的数据不大,最简单的方法就是在你的数据库中创建一个没有PK的临时表。然后将数据插入到该临时表中,从临时表中删除重复项(如果您有 SQL Server 数据库,您可以使用以下语法删除重复项)并将数据插入到主表中。

 WITH table_1 AS 
(SELECT *,RN=ROW_NUMBER() OVER(PARTITION BY [pk_field]
order by date)
FROM [temporary_table])
DELETE FROM table_1 WHERE RN>1

关于python - 如何使用 pyodbcexecutemany() 处理主键约束违规,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54308346/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com