xcode 在 swift 中设置关系数据库 (sqlite) 的步骤

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27748838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:26:40  来源:igfitidea点击:

Steps to setting up relational database (sqlite) in swift

iosxcodeswiftsqlite

提问by GenerationDebt

I am working on an iOS app and I want to set up a relational database for it. I read that SQLite is a good database to use. I'm making the app in Swift. I've looked at several tutorials but it seems like all the ones that I found have the DBManager class or libraries in objective-c. Therefore, I would need a wrapper for the db class. I'm not really sure how the wrapper works and how I would be calling objective-c methods using swift syntax.

我正在开发一个 iOS 应用程序,我想为它设置一个关系数据库。我读到 SQLite 是一个很好的数据库。我正在 Swift 中制作应用程序。我看过几个教程,但似乎我发现的所有教程都在objective-c 中有 DBManager 类或库。因此,我需要一个 db 类的包装器。我不太确定包装器是如何工作的,以及我将如何使用 swift 语法调用 Objective-c 方法。

I was wondering if someone could help clarify the whole process for this from creating the database file and adding it to your xcode project to using objective-c libraries with swift syntax in order to run queries against the database file.

我想知道是否有人可以帮助澄清从创建数据库文件并将其添加到您的 xcode 项目到使用具有 swift 语法的objective-c 库以便对数据库文件运行查询的整个过程。

Also, is it worth it to just use Core Data which seems easier to use instead?

另外,仅使用看起来更容易使用的 Core Data 是否值得?

回答by stephencelis

Objective-C tutorials are still more-or-less relevant, but obviously won't bring Swift-specific niceties into the fold (nor does FMDB, currently, as recommended by another commenter). I ended up writing SQLite.swiftto utilize some of the more interesting aspects of Swift (type-safety and generics, optionals):

Objective-C 教程仍然或多或少相关,但显然不会将 Swift 特定的细节带入折叠中(FMDB 目前也没有,正如另一位评论者所推荐的那样)。我最终编写了SQLite.swift来利用 Swift 的一些更有趣的方面(类型安全和泛型,可选):

https://github.com/stephencelis/SQLite.swift

https://github.com/stephencelis/SQLite.swift

SQLite.swift provides compile-time safety/confidence, and removes the need for a lot of error handling. Statements and expressions are built in Swift proper, so runtime SQL syntax errors are unlikely.

SQLite.swift 提供编译时安全/信心,并消除了对大量错误处理的需要。语句和表达式是在 Swift 中构建的,因此运行时 SQL 语法错误的可能性很小。

See the documentationfor more information on creating the database file and where to store it (depending on your needs):

有关创建数据库文件及其存储位置的更多信息,请参阅文档(取决于您的需要):

https://github.com/stephencelis/SQLite.swift/blob/master/Documentation/Index.md#connecting-to-a-database

https://github.com/stephencelis/SQLite.swift/blob/master/Documentation/Index.md#connecting-to-a-database

As far as Core Data is concerned, it (like most Apple libraries at the time of this answer) doesn't take advantage of Swift, but has a rich legacy and may be the way to go, especially for a smaller, persistent object graph. However, if you want control over a relational database, or if you plan on storing a large dataset that changes frequently, you may become frustrated with Core Data (and the domain-specific knowledge you'll need to attain),

就 Core Data 而言,它(与本回答时的大多数 Apple 库一样)没有利用 Swift,但具有丰富的遗产,可能是要走的路,尤其是对于较小的持久对象图. 但是,如果您想要控制关系数据库,或者如果您计划存储经常更改的大型数据集,您可能会对 Core Data(以及您需要获得的特定领域知识)感到沮丧,

回答by Yash Tamakuwala

I have myself followed this step by step and well explained tutorial by techtopia.

我自己一步一步地遵循了这一点,并由 techtopia 很好地解释了教程。

http://www.techotopia.com/index.php/Swift_iOS_8_Database_Implementation_using_SQLite

http://www.techotopia.com/index.php/Swift_iOS_8_Database_Implementation_using_SQLite

http://www.techotopia.com/index.php/An_Example_SQLite_based_iOS_8_Application_using_Swift_and_FMDB

http://www.techotopia.com/index.php/An_Example_SQLite_based_iOS_8_Application_using_Swift_and_FMDB

It uses FMDB wrapper.

它使用 FMDB 包装器。

Creating the Database and Table

创建数据库和表

override func viewDidLoad() {
super.viewDidLoad()

let filemgr = NSFileManager.defaultManager()
let dirPaths =
NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
        .UserDomainMask, true)

let docsDir = dirPaths[0] as! String

databasePath = docsDir.stringByAppendingPathComponent(
                "contacts.db")

if !filemgr.fileExistsAtPath(databasePath as String) {

    let contactDB = FMDatabase(path: databasePath as String)

    if contactDB == nil {
        println("Error: \(contactDB.lastErrorMessage())")
    }

    if contactDB.open() {
        let sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)"
        if !contactDB.executeStatements(sql_stmt) {
            println("Error: \(contactDB.lastErrorMessage())")
        }
        contactDB.close()
    } else {
        println("Error: \(contactDB.lastErrorMessage())")
    }
}
}

The code in the above method performs the following tasks:

上述方法中的代码执行以下任务:

-Identifies the application's Documents directory and constructs a path to the contacts.db database file.

- 标识应用程序的 Documents 目录并构建一个到contacts.db 数据库文件的路径。

-Creates an NSFileManager instance and subsequently uses it to detect if the database file already exists.

- 创建一个 NSFileManager 实例并随后使用它来检测数据库文件是否已经存在。

-If the file does not yet exist the code creates the database by creating an FMDatabase instance initialized with the database file path. If the database creation is successful it is then opened via a call to the open method of the new database instance.

- 如果文件尚不存在,则代码通过创建使用数据库文件路径初始化的 FMDatabase 实例来创建数据库。如果数据库创建成功,则通过调用新数据库实例的 open 方法将其打开。

-Prepares a SQL statement to create the contacts table in the database and executes it via a call to the FMDB executeStatements method of the database instance.

- 准备一条 SQL 语句以在数据库中创建联系人表,并通过调用数据库实例的 FMDB executeStatements 方法来执行它。

-Closes the database.

- 关闭数据库。

SAVE DATA TO DATABASE

将数据保存到数据库

@IBAction func saveData(sender: AnyObject) {
let contactDB = FMDatabase(path: databasePath as String)

if contactDB.open() {

    let insertSQL = "INSERT INTO CONTACTS (name, address, phone) VALUES ('\(name.text)', '\(address.text)', '\(phone.text)')"

    let result = contactDB.executeUpdate(insertSQL, 
        withArgumentsInArray: nil)

    if !result {
        status.text = "Failed to add contact"
        println("Error: \(contactDB.lastErrorMessage())")
    } else {
        status.text = "Contact Added"
        name.text = ""
        address.text = ""
        phone.text = ""
    }
} else {
    println("Error: \(contactDB.lastErrorMessage())")
}
}

FETCH DATA FROM DATABASE

从数据库中获取数据

@IBAction func findContact(sender: AnyObject) {
let contactDB = FMDatabase(path: databasePath as String)

if contactDB.open() {
    let querySQL = "SELECT address, phone FROM CONTACTS WHERE name = '\(name.text)'"

    let results:FMResultSet? = contactDB.executeQuery(querySQL,
     withArgumentsInArray: nil)

    if results?.next() == true {
        address.text = results?.stringForColumn("address")
        phone.text = results?.stringForColumn("phone")
        status.text = "Record Found"
    } else {
        status.text = "Record not found"
        address.text = ""
        phone.text = ""
    }
    contactDB.close()
} else {
    println("Error: \(contactDB.lastErrorMessage())")
}
}

回答by Atamiri

You could use the sqlite wrapper included in this project. It's written in Objective-C but it can easily be used from within Swift.

您可以使用此项目中包含的 sqlite 包装器。它是用 Objective-C 编写的,但可以在 Swift 中轻松使用。

回答by Gwendal Roué

Yet another SQLite wrapper for Swift 3: http://github.com/groue/GRDB.swift

Swift 3 的另一个 SQLite 包装器:http: //github.com/groue/GRDB.swift

It provides:

它提供:

  • An API that will look familiar to users of the famous Objective-C FMDB (https://github.com/ccgus/fmdb)

  • A low-level SQLite API that leverages the Swift standard library.

  • A pretty Swift query interface for SQL-allergic developers

  • Support for the SQLite WAL mode, and concurrent database access for extra performance

  • A Record class that wraps result sets, eats your custom SQL queries for breakfast, provides persistence operations, and changes tracking.

  • Swift type freedom: pick the right Swift type that fits your data. Use Int64 when needed, or stick with the convenient Int. Store and read NSDate or NSDateComponents. Declare Swift enums for discrete data types. Define your own database-convertible types.

  • Database migrations

  • Speed: https://github.com/groue/GRDB.swift/wiki/Performance

  • 著名的 Objective-C FMDB ( https://github.com/ccgus/fmdb) 的用户看起来很熟悉的 API

  • 利用 Swift 标准库的低级 SQLite API。

  • 一个非常适合 SQL 过敏开发人员的 Swift 查询界面

  • 支持 SQLite WAL 模式和并发数据库访问以提高性能

  • 一个 Record 类,它包装结果集、吃你的自定义 SQL 查询作为早餐、提供持久性操作和更改跟踪。

  • Swift 类型自由:选择适合您数据的正确 Swift 类型。需要时使用 Int64,或坚持使用方便的 Int。存储和读取 NSDate 或 NSDateComponents。为离散数据类型声明 Swift 枚举。定义您自己的数据库可转换类型。

  • 数据库迁移

  • 速度:https: //github.com/groue/GRDB.swift/wiki/Performance