在MySQL中,你可以像这样插入多行:

INSERT INTO 'tablename' ('column1', 'column2') VALUES
    ('data1', 'data2'),
    ('data1', 'data2'),
    ('data1', 'data2'),
    ('data1', 'data2');

然而,当我尝试这样做时,我得到了一个错误。是否可以在SQLite数据库中一次插入多行?这样做的语法是什么?


当前回答

我很惊讶没有人提到事先准备好的声明。除非您单独使用SQL而不是在任何其他语言中使用,否则我认为将准备好的语句包装在事务中是插入多行最有效的方式。

其他回答

简单。自我解释。

在版本3.36.0 11/20/21上进行测试。

CREATE TEMP TABLE x (col1 TEXT, col2 TEXT, col3 TEXT);

INSERT INTO x 
VALUES 
('xx','yy','cc'),
('xx','yy','cc'),
('xx','yy','cc'),
('xx','yy','cc'),
('xx','yy','cc'),
('xx','yy','cc');

SELECT * FROM x;

输出:

col1|col2|col3|
----+----+----+
xx  |yy  |cc  |
xx  |yy  |cc  |
xx  |yy  |cc  |
xx  |yy  |cc  |
xx  |yy  |cc  |
xx  |yy  |cc  |

版本检查:

SELECT sqlite_version();

输出:

sqlite_version()|
----------------+
3.36.0          |

有些人可能会说-所有的“..”的答案已经过时了;尽管如此,它们还是非常有用的。有时候,我们都坐在桌子上“过去的爆炸”,然后15年前的纸条拯救了我们的一天。

如果您使用Sqlite管理器firefox插件,它支持从INSERT SQL语句批量插入。

事实上,它不支持这一点,但Sqlite浏览器做(适用于Windows, OS X, Linux)

我有一个像下面这样的查询,但与ODBC驱动程序SQLite有一个错误“,”它说。 我运行vbscript在HTA (Html应用程序)。

    INSERT INTO evrak_ilac_iliskileri (evrak_id, ilac_id, 
baglayan_kullanici_id, tarih) VALUES (4150,762,1,datetime()),
(4150,9770,1,datetime()),(4150,6609,1,datetime()),(4150,3628,1,datetime()),
(4150,9422,1,datetime())

Alex是正确的:“select…”“Union”语句将失去对某些用户非常重要的排序。即使当您以特定的顺序插入时,sqlite也会更改内容,因此如果插入顺序很重要,则更倾向于使用事务。

create table t_example (qid int not null, primary key (qid));
begin transaction;
insert into "t_example" (qid) values (8);
insert into "t_example" (qid) values (4);
insert into "t_example" (qid) values (9);
end transaction;    

select rowid,* from t_example;
1|8
2|4
3|9

如果你正在使用bash shell,你可以使用这个:

time bash -c $'
FILE=/dev/shm/test.db
sqlite3 $FILE "create table if not exists tab(id int);"
sqlite3 $FILE "insert into tab values (1),(2)"
for i in 1 2 3 4; do sqlite3 $FILE "INSERT INTO tab (id) select (a.id+b.id+c.id)*abs(random()%1e7) from tab a, tab b, tab c limit 5e5"; done; 
sqlite3 $FILE "select count(*) from tab;"'

或者如果你在sqlite CLI中,那么你需要这样做:

create table if not exists tab(id int);"
insert into tab values (1),(2);
INSERT INTO tab (id) select (a.id+b.id+c.id)*abs(random()%1e7) from tab a, tab b, tab c limit 5e5;
INSERT INTO tab (id) select (a.id+b.id+c.id)*abs(random()%1e7) from tab a, tab b, tab c limit 5e5;
INSERT INTO tab (id) select (a.id+b.id+c.id)*abs(random()%1e7) from tab a, tab b, tab c limit 5e5;
INSERT INTO tab (id) select (a.id+b.id+c.id)*abs(random()%1e7) from tab a, tab b, tab c limit 5e5;
select count(*) from tab;

它是如何工作的? 它使用if表选项卡:

id int
------
1
2

然后从TAB a中选择a.id, b.id, TAB b返回

a.id int | b.id int
------------------
    1    | 1
    2    | 1
    1    | 2
    2    | 2

等等。第一次执行后,插入2行,然后2^3=8。(三个,因为我们有TAB a TAB b TAB c)

在第二次执行之后,我们插入额外的(2+8)^3=1000行

第三次之后,我们插入大约max(1000^ 3,5e5)=500000行,依此类推……

这是我所知道的填充SQLite数据库的最快方法。