Sqlite.swift: Inserting Multiple Rows At Once

Created on 26 Apr 2017  路  9Comments  路  Source: stephencelis/SQLite.swift

I tried to search the docs but found nothing, is it possible to insert multiple rows at once?

Most helpful comment

would like this feature also

All 9 comments

Could you be more specific or what's to goal that you want to achieve?

How can I do something like that:

INSERT INTO mytable (col1, col2, col3) VALUES
    (1, 2, "abc"),
    (2, 4, "xyz"),
    (3, 5, "aaa"),
    (4, 7, "bbb");

You could do it with an SQL statement like you've wrote.

I've posted a sample SQL-Statement here: https://github.com/stephencelis/SQLite.swift/issues/626

Or you could write a loop and do it with the SQLite way from the documentation:

for user in usersArray {
    try db.run(users.insert(email <- user.email, name <- user.name))
    // INSERT INTO "users" ("email", "name") VALUES (UserEmail, UserName)
}

I haven't tested this.

That's just workarounds I already did use plain sql statements, but would be nice to have it supported.

Well maybe @stephencelis or one of the contributors will comment on this, but I don't see the loop-way as a workaround. I would go that way.

would like this feature also

That would be an awesome feature ... I've searched the docs for something similar but had to use an SQL statement at the end

Is there still a way to insert multiple rows in one go ?

You can add them in a single transaction:

try db!.transaction {
    for user in usersArray {
        try db.run(users.insert(email <- user.email, name <- user.name))
        // INSERT INTO "users" ("email", "name") VALUES (UserEmail, UserName)
    }
}
Was this page helpful?
0 / 5 - 0 ratings