在MySQL中,你可以像这样插入多行:
INSERT INTO 'tablename' ('column1', 'column2') VALUES
('data1', 'data2'),
('data1', 'data2'),
('data1', 'data2'),
('data1', 'data2');
然而,当我尝试这样做时,我得到了一个错误。是否可以在SQLite数据库中一次插入多行?这样做的语法是什么?
在MySQL中,你可以像这样插入多行:
INSERT INTO 'tablename' ('column1', 'column2') VALUES
('data1', 'data2'),
('data1', 'data2'),
('data1', 'data2'),
('data1', 'data2');
然而,当我尝试这样做时,我得到了一个错误。是否可以在SQLite数据库中一次插入多行?这样做的语法是什么?
当前回答
从版本2012-03-20(3.7.11)开始,sqlite支持以下INSERT语法:
INSERT INTO 'tablename' ('column1', 'column2') VALUES
('data1', 'data2'),
('data3', 'data4'),
('data5', 'data6'),
('data7', 'data8');
阅读文档:http://www.sqlite.org/lang_insert.html
PS:请给Brian Campbell的回复+1。不是我的!他首先提出了解决方案。
其他回答
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.
我有一个像下面这样的查询,但与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())
Fearless_fool对于旧版本有一个很好的答案。我只是想补充一下,你需要确保你列出了所有的列。如果你有3列,你需要确保select作用在3列上。
示例:我有3列,但我只想插入2列的数据。假设我不关心第一列因为它是一个标准整数id。我可以这样做……
INSERT INTO 'tablename'
SELECT NULL AS 'column1', 'data1' AS 'column2', 'data2' AS 'column3'
UNION SELECT NULL, 'data3', 'data4'
UNION SELECT NULL, 'data5', 'data6'
UNION SELECT NULL, 'data7', 'data8'
注意:记住“select…”“工会”的声明将失去秩序。(从AG1)
你不能,但我不认为你错过了什么。
因为sqlite总是在进程中调用,所以执行1条插入语句还是100条插入语句对性能几乎没有影响。然而,提交需要花费很多时间,所以将这100个插入放在事务中。
当你使用参数化查询时,Sqlite要快得多(需要的解析要少得多),所以我不会像这样串联大语句:
insert into mytable (col1, col2)
select 'a','b'
union
select 'c','d'
union ...
它们需要一遍又一遍地解析,因为每个连接的语句都是不同的。
正如其他人所说,SQLite不支持这种语法。我不知道复合insert是否是SQL标准的一部分,但根据我的经验,它们在许多产品中都没有实现。
顺便说一句,您应该意识到,如果在显式事务中包装多个INSERT, SQLite中的INSERT性能将大大提高。