Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 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


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

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...