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

后端 未结 24 2876
猫巷女王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:40

    If you are using bash shell you can use this:

    time bash -c $'
    FILE=/dev/shm/test.db
    sqlite3 $FILE "create table if not exists tab(id int);"
    sqlite3 $FILE "insert into tab values (1),(2)"
    for i in 1 2 3 4; do sqlite3 $FILE "INSERT INTO tab (id) select (a.id+b.id+c.id)*abs(random()%1e7) from tab a, tab b, tab c limit 5e5"; done; 
    sqlite3 $FILE "select count(*) from tab;"'
    

    Or if you are in sqlite CLI, then you need to do this:

    create table if not exists tab(id int);"
    insert into tab values (1),(2);
    INSERT INTO tab (id) select (a.id+b.id+c.id)*abs(random()%1e7) from tab a, tab b, tab c limit 5e5;
    INSERT INTO tab (id) select (a.id+b.id+c.id)*abs(random()%1e7) from tab a, tab b, tab c limit 5e5;
    INSERT INTO tab (id) select (a.id+b.id+c.id)*abs(random()%1e7) from tab a, tab b, tab c limit 5e5;
    INSERT INTO tab (id) select (a.id+b.id+c.id)*abs(random()%1e7) from tab a, tab b, tab c limit 5e5;
    select count(*) from tab;
    

    How does it work? It makes use of that if table tab:

    id int
    ------
    1
    2
    

    then select a.id, b.id from tab a, tab b returns

    a.id int | b.id int
    ------------------
        1    | 1
        2    | 1
        1    | 2
        2    | 2
    

    and so on. After first execution we insert 2 rows, then 2^3=8. (three because we have tab a, tab b, tab c)

    After second execution we insert additional (2+8)^3=1000 rows

    Aftern thrid we insert about max(1000^3, 5e5)=500000 rows and so on...

    This is the fastest known for me method of populating SQLite database.

提交回复
热议问题