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

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

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


当前回答

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.

其他回答

从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

INSERT INTO TABLE_NAME 
            (DATA1, DATA2) 
VALUES      (VAL1, VAL2), 
            (VAL1, VAL2), 
            (VAL1, VAL2), 
            (VAL1, VAL2), 
            (VAL1, VAL2), 
            (VAL1, VAL2), 
            (VAL1, VAL2), 
            (VAL1, VAL2); 

你可以使用InsertHelper,它简单快捷

文档: http://developer.android.com/reference/android/database/DatabaseUtils.InsertHelper.html

教程: http://www.outofwhatbox.com/blog/2010/12/android-using-databaseutils-inserthelper-for-faster-insertions-into-sqlite-database/

编辑: 从API级别17开始,InsertHelper已弃用

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

你不能,但我不认为你错过了什么。

因为sqlite总是在进程中调用,所以执行1条插入语句还是100条插入语句对性能几乎没有影响。然而,提交需要花费很多时间,所以将这100个插入放在事务中。

当你使用参数化查询时,Sqlite要快得多(需要的解析要少得多),所以我不会像这样串联大语句:

insert into mytable (col1, col2)
select 'a','b'
union 
select 'c','d'
union ...

它们需要一遍又一遍地解析,因为每个连接的语句都是不同的。