Is it possible to insert multiple rows at a time in an SQLite database?

后端 未结 24 2878
猫巷女王i
猫巷女王i 2020-11-21 06:12

In MySQL you can insert multiple rows like this:

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


        
24条回答
  •  离开以前
    2020-11-21 06:34

    Sqlite3 can't do that directly in SQL except via a SELECT, and while SELECT can return a "row" of expressions, I know of no way to make it return a phony column.

    However, the CLI can do it:

    .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> 
    

    If you do put a loop around an INSERT, rather than using the CLI .import command, then be sure to follow the advice in the sqlite FAQ for INSERT speed:

    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.

提交回复
热议问题