gpt4 book ai didi

sqlite - 消除 sqlite 中的唯一约束错误

转载 作者:行者123 更新时间:2023-12-02 12:46:49 26 4
gpt4 key购买 nike

我正在将 CSV 加载到 sqlite 数据库,如下所示:

sqlite3 /path/to/output.db < /path/to/sqlite_commands.sql

sqlite 命令文件如下所示:

sqlite_commands.sql

CREATE TABLE products (
"c1" TEXT PRIMARY KEY NOT NULL,
"c2" TEXT,
"c3" TEXT
);
.mode csv

.import /tmp/csv_with_dups.csv products

csv 看起来像

/tmp/csv_with_dups.csv

c1,c2,c3
a,b,c
b,c,d
c,d,e
d,e,f
a,a,b
e,f,g

我收到 stderr 错误

/tmp/csv_with_dups.csv.tmp:6: INSERT failed: UNIQUE constraint failed: products.c1

我想消除此错误,因为我们知道某些 csv 有重复项(csv 是由单独的机制在非常大的数据集上生成的,无法在该阶段验证重复项)

我尝试根据文档添加此行

.log off 

also tried
.log stderr|off

also tried
.log stderr off

sqlite3
.help
...
.log FILE|off Turn logging on or off. FILE can be stderr/stdout
...

最佳答案

“INSERT failed”消息始终打印到 stderr。

您可以忽略 stderr,但这也会抑制所有其他错误消息:

sqlite3 ... 2>/dev/null

或者,您可以自己生成 SQL 命令,以便可以使用 INSERT 或 IGNORE:

import sys
import csv

def quote_sql_str(s):
return "'" + s.replace("'", "''") + "'"

print('BEGIN;')
with open(sys.argv[1], 'rb') as file:
for row in csv.reader(file):
print('INSERT OR IGNORE INTO products VALUES({});'
.format(','.join([quote_sql_str(s) for s in row])))
print('COMMIT;')
python script.py csv_with_dups.csv | sqlite3 /path/to/output.db

或者,导入到没有约束的临时表中,然后使用 INSERT OR IGNORE 复制到实际表中。

关于sqlite - 消除 sqlite 中的唯一约束错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47410663/

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