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

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

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


当前回答

从3.7.11版本开始,SQLite支持多行插入。理查德。 Hipp评论:

我使用的是3.6.13

我这样命令:

insert into xtable(f1,f2,f3) select v1 as f1, v2 as f2, v3 as f3 
union select nextV1+, nextV2+, nextV3+

一次插入50条记录,只需要一秒钟或更短的时间。

确实,使用sqlite一次插入多行是非常可能的。作者@Andy写道。

谢谢Andy

其他回答

是的,从SQLite 3.7.11开始,SQLite支持这一点。从SQLite文档:

(当这个答案最初写的时候,这是不支持的)

为了兼容旧版本的SQLite,你可以使用andy和fearless_fool所建议的技巧,使用UNION,但对于3.7.11及以后版本,这里描述的更简单的语法应该是首选。

Sqlite3不能在SQL中直接做到这一点,除非通过一个SELECT,虽然SELECT可以返回一个“行”表达式,但我知道没有办法让它返回一个假列。

但是,CLI可以做到:

.import FILE TABLE     Import data from FILE into TABLE
.separator STRING      Change separator used by output mode and .import

$ sqlite3 /tmp/test.db
SQLite version 3.5.9
Enter ".help" for instructions
sqlite> create table abc (a);
sqlite> .import /dev/tty abc
1
2
3
99
^D
sqlite> select * from abc;
1
2
3
99
sqlite> 

如果你在INSERT中使用了一个循环,而不是使用CLI .import命令,那么一定要遵循sqlite FAQ中的建议来提高INSERT速度:

By default, each INSERT statement is its own transaction. But if you surround multiple INSERT statements with BEGIN...COMMIT then all the inserts are grouped into a single transaction. The time needed to commit the transaction is amortized over all the enclosed insert statements and so the time per insert statement is greatly reduced. Another option is to run PRAGMA synchronous=OFF. This command will cause SQLite to not wait on data to reach the disk surface, which will make write operations appear to be much faster. But if you lose power in the middle of a transaction, your database file might go corrupt.

我编写了一些ruby代码,从一系列插入语句中生成一个500个元素的多行插入,这比运行单个插入快得多。然后我尝试简单地将多个插入打包到一个事务中,发现我可以用更少的代码获得同样的速度。

BEGIN TRANSACTION;
INSERT INTO table VALUES (1,1,1,1);
INSERT INTO table VALUES (2,2,2,2);
...
COMMIT;

是的,sql可以做到这一点,但是使用不同的语法。顺便说一下,sqlite文档非常好。它还会告诉您插入几行的唯一方法是使用select语句作为要插入的数据的源。

正如其他人所说,SQLite不支持这种语法。我不知道复合insert是否是SQL标准的一部分,但根据我的经验,它们在许多产品中都没有实现。

顺便说一句,您应该意识到,如果在显式事务中包装多个INSERT, SQLite中的INSERT性能将大大提高。