我有一个脚本,可以使用executemany()
在表中插入数据帧。
问题是此表具有 ID 作为主键,有时可能会插入具有相同 ID 的行。
我想知道是否有一种简单的方法来处理这种异常并继续executemany()
执行。
我正在考虑的替代方案是检查表中数据帧的所有 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