Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

ios - Swift: Open/create SQLite database works on simulator but not on iPhone

I am new to Swift, Xcode and SQLite. Trying to open/create a database and create a table. It works on the simulator but not on my iPhone. Would appreciate if anyone could help me figure this out.

func openDatabase() -> OpaquePointer? {
    let filePath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathExtension(path)
    
    var db : OpaquePointer? = nil
    
    // Check for error in creating db or return database
    if sqlite3_open(filePath.path, &db) != SQLITE_OK {
        print("Error in creating database.")
        let errorMessage = String(cString: sqlite3_errmsg(db))
        print(errorMessage)
        sqlite3_close(db)
        db = nil
        return nil
    } else {
        print("Database has been created with path (path)")
        return db
    }
}

//Create database table with query
func createTable(){
    let query = "CREATE TABLE IF NOT EXISTS prime(primenumber INTEGER, date TEXT);"
    var createTable : OpaquePointer? = nil
    
    if sqlite3_prepare_v2(self.db, query, -1, &createTable, nil) == SQLITE_OK {
        if sqlite3_step(createTable) == SQLITE_DONE { //table is created
            print("Table successfully created.")
        } else {
            print("Table creation failed.")
        }
    } else {
        print("Table preparation failed.")
        let errorMessage = String(cString: sqlite3_errmsg(db))
        print(errorMessage)
    }
}

Error message:

2021-01-06 17:25:22.308037+0100 SQLiteTest[3691:955723] [logging-persist] cannot open file at line 43353 of [378230ae7f] 2021-01-06 17:25:22.308134+0100 SQLiteTest[3691:955723] [logging-persist] os_unix.c:43353: (0) open(/var/mobile/Containers/Data/Application/D0AEB9BE-E286-4755-B4DD-813F7EA1935D/Documents.myDb.sqlite) - Undefined error: 0 Error in creating database. unable to open database file

2021-01-06 17:25:22.308955+0100 SQLiteTest[3691:955723] [logging] API call with NULL database connection pointer 2021-01-06 17:25:22.309016+0100 SQLiteTest[3691:955723] [logging] misuse at line 131400 of [378230ae7f] Table preparation failed. out of memory

question from:https://stackoverflow.com/questions/65599621/swift-open-create-sqlite-database-works-on-simulator-but-not-on-iphone

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...