Fangming
Fangming

Reputation: 25261

Swift sqlite How to run multiple queries (inserts, updates, etc) in one string

I am using the sqlite3 library in swift, trying to run multiple insert statements separated by semi colon, like this:

INSERT INTO PARAMS VALUES ('t1', 'r1');INSERT INTO PARAMS VALUES ('t2', 'r2');...;...;

The code I currently have is:

let multiQueries= "INSERT INTO PARAMS VALUES ('t1', 'r1');INSERT INTO PARAMS VALUES ('t2', 'r2');"
var queryStatement: OpaquePointer? = nil
if sqlite3_prepare_v2(dbPointer, multiQueries, -1, &queryStatement, nil) == SQLITE_OK {
    if sqlite3_step(queryStatement) != SQLITE_DONE {
        print("Cannot execute query")
    }else{
        print("ok")
    }
} else {
    print("Queries could not be prepared")
}

But only the first query is executed. I tried to do multiple sqlite3_step like doing a select statement, but the second time I call it, it returns error code 21.

Upvotes: 0

Views: 1165

Answers (1)

Fangming
Fangming

Reputation: 25261

Here is the answer, credits for @rmaddy for the hint. The following code works fine for me.

var errMsg: UnsafeMutablePointer<Int8>? = nil
if sqlite3_exec(dbPointer, multiQueries, nil, nil, &errMsg) != SQLITE_OK {
    print("Cannot execute query")
    if let errMsg = errMsg {
        print(String(cString: errMsg))
    }
}else{
    print("ok")
}

From sqlite documents, sqlite3_step is for queries with results like selects, and sqlite3_exec is for queries with no results like inserts.

Upvotes: 5

Related Questions