简体   繁体   中英

Why doesn't Xcode / SQLite.swift recognize my .db file as a database?

I'm using SQLite.swift to run queries on a .db file in my Xcode project, and I keep receiving "code: 26 -- file is not a database" when I try to connect to the database from the documents folder on the device.

When I use the file path to the .db file in on my desktop, it has no problem running my queries. When I add the file to Xcode, however, it comes up with code 26 whether I try to access it from the Bundle.main path or when I copy it to the device's documents folder and try to access it there. If I use the terminal to open the database, it opens in my SQLite viewer just as it would if I accessed it in my desktop. Thus, I know it is a .db file, I know my code can work with this file, but when I try to access it on the device, it somehow doesn't recognize it as a database!

Thanks for your help. This has been plaguing me for days, and I can't figure out what the heck is going on!

below is yours answers


class SqliteDB{
    static let shared:SqliteDB = SqliteDB()
    private init(){}
    
    var DB:Connection!
    
    /// path for creat a databased file.
    func createDBPath(){
        do {
            let dbPath = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("chatDB.sqlite").path
            DB = try Connection(dbPath)
            print(dbPath)

        } catch {
            print(error.localizedDescription)
        }
    }
    
    func dbTables_ChatMessage(){
        let tableQuery = """
           CREATE TABLE IF NOT EXISTS message_list (id INTEGER, conversation_id INTEGER UNIQUE, conversation_recipient_id INTEGER, timestamp INTEGER UNIQUE, content_type TEXT, message TEXT, user_id INTEGER, user_name TEXT, group_id INTEGER,isOnline TEXT,room_id INTEGER, local_conversation_id INTEGER ,room_unique_id TEXT,PRIMARY KEY(id AUTOINCREMENT))
          """
        do {
            try DB.run(tableQuery)
        } catch  {
            print(error.localizedDescription)
        }
    }
  }

use singleton access this class objects

SqliteDB.shared.createDBPath(). // use in a--delegates when app is launch SQliteDb create a path as well as databases

SqliteDB.shared. dbTables_ChatMessage() where you want to create table 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM