在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数据库中一次插入多行?这样做的语法是什么?
当前回答
如果您使用Sqlite管理器firefox插件,它支持从INSERT SQL语句批量插入。
事实上,它不支持这一点,但Sqlite浏览器做(适用于Windows, OS X, Linux)
其他回答
从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
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.
我很惊讶没有人提到事先准备好的声明。除非您单独使用SQL而不是在任何其他语言中使用,否则我认为将准备好的语句包装在事务中是插入多行最有效的方式。
从版本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。不是我的!他首先提出了解决方案。
使用事务的问题是,您还锁定了用于读取的表。所以,如果你有很多数据要插入,你需要访问你的数据,例如预览之类的,这种方式就不太适用了。
另一个解决方案的问题是,您失去了插入的顺序
insert into mytable (col)
select 'c'
union
select 'd'
union
select 'a'
union
select 'b';
在sqlite中,数据将被存储为a,b,c,d…