Home > database >  Problem With Sqlite3 Database Using Swift
Problem With Sqlite3 Database Using Swift

Time:11-07

I have been trying to figure out my logic. I perform the following to open my database:

func createDB() -> OpaquePointer?{
        
    var db : OpaquePointer?
    
    guard sqlite3_open(path, &db) == SQLITE_OK else {
        print("error opening database")
        sqlite3_close(db)
        db = nil
        return nil
    }
    
    return db
}

I then try to perform the following select statement:

let queryString = "select photo_id from unsplash_photos"
        
var statement: OpaquePointer?

if(sqlite3_prepare_v2(db, queryString, -1, &statement, nil)) != SQLITE_OK {
    let errmsg = String(cString: sqlite3_errmsg(db)!)
        print("error preparing select: \(errmsg)")
}

var rc = sqlite3_step(statement)

while rc == SQLITE_ROW {
    print("row",rc)
    
    rc = sqlite3_step(statement)
}

When this runs the result is printing 100 for every step.

row 100
row 100
row 100
row 100
row 100
row 100
row 100
row 100
row 100

Does this have something to do with how the database is setup? Does this have to do with how the tables are situated?

CodePudding user response:

SQLITE_ROW is a condition code whose value is 100. It means "sqlite3_step() has another row ready" according to this page. It it is not the number of the row returned.

CodePudding user response:

Yes, it is telling you that it found 9 rows of data, returning SQLITE_ROW (100) each time. If you want to do extract the data, you have to call sqlite3_column_xxx() to get the data for the respective row. E.g., sqlite3_column_int if the photo_id is an integer:

let queryString = "select photo_id from unsplash_photos"

var statement: OpaquePointer?

guard sqlite3_prepare_v2(db, queryString, -1, &statement, nil) == SQLITE_OK else {
    let errmsg = String(cString: sqlite3_errmsg(db)!)
    print("error preparing select: \(errmsg)")
    return
}

var rc = sqlite3_step(statement)

// as long as there's a row of data returned, display it

while rc == SQLITE_ROW {
    let id = sqlite3_column_int(statement, 0)
    print("id =", id)

    rc = sqlite3_step(statement)
}

// at the end, we should have gotten `SQLITE_DONE`, and if not, show the error

if rc != SQLITE_DONE {
    let errmsg = String(cString: sqlite3_errmsg(db)!)
    print("rc =", rc, "error = ", errmsg)
}

// clean up when we're done

sqlite3_finalize(statement)
  • Related