Skip to content
Advertisement

How to use “select * table where * = ?” in Swift with Sqlite3

I’m using SQLlite3 for my database and i’m trying use “select * table where * = ?” in Swift with Sqlite3 but I’m stuck using where here’s the method I used but i get no response from the methode .

    func DoesExist(titles: String?){

        ArticleList.removeAll()
        let queryStrings = "SELECT * FROM articles WHERE title = ? "
        var stmt3:OpaquePointer?
        if sqlite3_prepare(db, queryStrings, -1, &stmt3, nil) != SQLITE_OK{
            let errmsg = String(cString: sqlite3_errmsg(db)!)
            print("error preparing Select: (errmsg)")
            return
        }
        if sqlite3_bind_text(stmt3, 1, titles, -1, nil) != SQLITE_OK{
            let errmsg = String(cString: sqlite3_errmsg(db)!)
            print("failure binding title: (errmsg)")
            return
        }

        while(sqlite3_step(stmt3) == SQLITE_ROW){
            let id = sqlite3_column_int(stmt3, 0)
            let author = String(cString: sqlite3_column_text(stmt3, 1))
            let title = sqlite3_column_int(stmt3, 2)

            //adding values to list
            ArticleList.append(Article(id: Int(id), author: String(describing: author), title: String(describing: title)))
             print(ArticleList.count)
 }

    }

i don’t know if that helps but when i try printing sqlite3_step(stmt3) i get 101 I don’t get what I did wrong so if anyone is familiar with this error help, please?

*****UPDATE*****

i added

if sqlite3_step(stmt3) != SQLITE_DONE {
        let errmsg = String(cString: sqlite3_errmsg(db)!)
        print("failure inserting foo: (errmsg)")
    }
    print("---------------------(sqlite3_step(stmt3))")

and istead of getting 101 i got 21 which means : out of memory

Advertisement

Answer

The (admittedly misleading) “out of memory” error is SQLite’s way of saying that the db pointer is nil. Print/test db before the sqlite3_xxx call that gave you the “out of memory” error, and you will see that it is, indeed, nil. If you are confident that you previously opened the database, then you must have some path of execution where you reset it to nil, or perhaps you have multiple db references floating about (e.g. some local var and the ivar).

You can add this test at the start of your method that has a precondition that the database must already be opened:

precondition(db != nil, "Database not open")
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement