0

我正在尝试将我的几个应用程序转换为使用 GRDB.swift。有人有或知道我在哪里可以找到一个文件让我开始吗?我已经阅读了大多数 GRDB 文档,但我没有得到它。下面是一个示例场景。

这我能够从 SQLite.sift 转换

class Database
{
    static let shared = Database()
    public let databaseConnection: DatabaseQueue?
    
    private init()
    {
        do
        {
            let fileUrl = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("MyDaatbase.sqlite")
            
            // GRDB
            let databaseConnection = try DatabaseQueue(path: fileUrl.path)
            self.databaseConnection = databaseConnection
        } catch {
            databaseConnection = nil
            let nserror = error as NSError
            print("Cannot connect to Database. Error is: \(nserror), \(nserror.userInfo)")
        }
    }
}

有人可以将其转换为 GRDB 以帮助我入门吗?

static func isAnimation() -> Bool
    {
        let theTable = Table("Settings")
        let theColumn = Expression<String>("AnimateNav")
        var theStatus = false
        
        do {
            for theAnswer in try Database.shared.databaseConnection!.prepare(theTable.select(theColumn)) {
                //print(theAnswer[theColumn])
                let theStatusText = (theAnswer[theColumn])
                
                theStatus = theStatusText == "true" ? true : false
            }
        } catch {
            print("Getting the isAnimation Status failed! Error: \(error)")
        }
        return theStatus
    }
4

1 回答 1

1

您可以使用原始 SQL:

static func isAnimation() -> Bool {
    var theStatus = false
    do {
        let animateNav = try Database.shared.databaseConnection!.read { db in
            String.fetchOne(db, sql: "SELECT AnimateNav FROM Settings")
        }
        theStatus = animateNav == "true" ? true : false
    } catch {
        print("Getting the isAnimation Status failed! Error: \(error)")
    }
    return theStatus
}

您还可以为表定义一个Record 类型Settings这是首选的 GRDB 方式:

// Settings.swift
struct Settings: Codable, FetchableRecord, TableRecord {
    var animateNav: String
    // other properties for other columns in the Settings table
    ...
}

// Your file
static func isAnimation() -> Bool {
    var theStatus = false
    do {
        let settings = try Database.shared.databaseConnection!.read { db in
            try Settings.fetchOne(db)
        }
        theStatus = settings?.animateNav == "true" ? true : false
    } catch {
        print("Getting the isAnimation Status failed! Error: \(error)")
    }
    return theStatus
}
于 2021-01-04T15:47:12.087 回答