使用Sqlite3和Python选择并插入大量数据

2024-09-25 00:36:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python创建一组字符串,并尝试查找该字符串是否在sqlite表中。如果是,我将把它插入另一个表。但是,为每个字符串值使用一个“LIKE”运算符需要花费太多时间。所以我试着把我要搜索的每一个字符串组合成一个SELECT

INSERT INTO table1 (ID, str0, str1, str2, str3) 
SELECT m.ID, m.str0, m.str1, m.str3, 2 FROM table2 m 
WHERE m.str0 LIKE "%xyz%" OR m.str0 LIKE "%asd%" OR m.str0 LIKE "%qwe%" ..... 
(goes on and on and on and on)

在一个INSERT中使用execute()创建了一个错误,即查询应该少于1000个字符。你知道吗

创建了一个l=[%xyz%,%asd%,%qwe%]的列表,并尝试使用executemany()

conn.executemany('INSERT INTO table1 (ID, str0, str1, str2, str3) 
SELECT m.ID, m.str0, m.str1, m.str2, 2 FROM table 2 m 
WHERE m.str0 LIKE ?',l)

但是它给出了一个错误“sqlite3.ProgrammingError:提供的绑定数量不正确。当前语句使用1,提供了5个

处理这类任务的最佳方法是什么?你知道吗


Tags: and字符串fromidonwhereselectlike
2条回答

executemany期望传递给函数的列表列表。使用二维而不是一维列表。另外,请注意,您正在向数据库中插入五个值,即“(ID,str0,str1,str2,str3)”,列表中提供了三个值。尝试添加更多值:

l = [[%xyz%, %asd%, %qwe%, %something%, %somethingelse%]]

对于这种情况,应该使用IN子句。你知道吗

SELECT * FROM table
WHERE table.str0 IN ('str1', 'str2', 'str3'); // With match any rows where str0 equals any of the passed values ('str1', 'str2', 'str3')

您可以阅读更多关于它的信息HERE。你知道吗

相关问题 更多 >