美文网首页Swift
[快速学会Swift第三方库] SQLite.swift篇

[快速学会Swift第三方库] SQLite.swift篇

作者: 远0 | 来源:发表于2018-07-11 14:32 被阅读139次

    SQLite.swift 是一个使用纯 Swift 语言封装 SQLite3 的操作框架。

    特性:

    1、简单的查询和参数绑定接口
    2、安全、自动类型数据访问
    3、隐式提交和回滚接口
    4、开发者友好的错误处理和调试
    5、文档完善
    6、通过广泛测试
    

    目录

    • [快速学会Swift第三方库 SQLiteswift篇]
      • [目录]
      • [编码之前]
        • [导入SQLiteswift]
        • [其他操作]
      • [链接数据库]
      • [创建表]
      • [插入数据]
      • [查询数据]
      • [修改数据]
      • [删除数据]
      • [深入学习]

    编码之前

    导入SQLite.swift

    推荐使用CocoaPods进行导入,CocoaPods是一个负责管理iOS项目中第三方开源库的工具,安装CocoaPods之后使用命令行就能轻松地对所有第三方开源库进行安装和更新,而不需要每次上GitHub去下载。
    CocoaPods的安装过程传送门:iOS 9 导入类库全面详尽过程(Ruby安装->CocoaPods安装->导入类库)
    手动下载:GitHub-SQLite.swift主页

    装好CocoaPods后,修改Podfile文件内容为如下:

    source 'https://github.com/CocoaPods/Specs.git'
    platform :ios, '9.0'
    use_frameworks!
    pod 'SQLite.swift', '~> 0.10.1'
    end
    xcodeproj 'Desktop/Web/Web.xcodeproj'
    

    target后面为工程名,最后一行为工程路径(这里的Web是我的工程名)

    再执行命令:

    pod install
    

    其他操作

    在Target->工程名->Build Settings->Search Paths->User Header Search Paths处添加SQLite.swift所在的目录:


    20160523181244677.png

    选择Target->工程名->Build Phases,在Link Binary With Libraries中添加 libsqlite3.tbd
    在工程的bridging header中加入以下代码:

    #import <sqlite3.h>
    

    最后在你需要用到SQLite.swift的类中加上:

    import SQLite
    

    链接数据库

    let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
    let db = try? Connection("\(path)/db.sqlite3")
    

    创建表

    let users = Table("users")
            let id = Expression<Int64>("id")
            let name = Expression<String?>("name")
            let email = Expression<String>("email")
    
            try! db?.run(users.create(ifNotExists: true, block: { (table) in
                table.column(id, primaryKey: true)
                table.column(name)
                table.column(email, unique: true)
            }))
    

    等价于执行SQL语句:

    CREATE TABLE IF NOT EXISTS "users" (
         "id" INTEGER PRIMARY KEY NOT NULL,
         "name" TEXT,
         "email" TEXT NOT NULL UNIQUE
    )
    

    插入数据

    let insert = users.insert(name <- "究极死胖兽", email <- "scuxiatian@foxmail.com")
    let rowid = (try! db?.run(insert))!
    let insert2 = users.insert(name <- "Amazing7", email <- "360898864@qq.com")
    let rowid2 = (try! db?.run(insert2))!
    

    等价于执行SQL语句:

    insert into users (name,email) values('究极死胖兽','scuxiatian@foxmail.com')
    insert into users (name,email) values('Amazing7','360898864@qq.com')
    

    查询数据

    for user in (try! db?.prepare(users))! {
                print("Query:id: \(user[id]), name: \(user[name]), email: \(user[email])")
            }
    

    等价于执行SQL语句:

    SELECT * FROM users
    

    执行结果:

    Query:id: 1, name: Optional("究极死胖兽"), email: scuxiatian@foxmail.com
    Query:id: 2, name: Optional("Amazing7"), email: 360898864@qq.com
    

    条件查询会在后面用到

    修改数据

    let update = users.filter(id == rowid)
    try! db?.run(update.update(email <- email.replace("foxmail", with: "qq")))
    
    for user in (try! db?.prepare(users.filter(name == "究极死胖兽")))! {
        print("Update:id: \(user[id]), name: \(user[name]), email: \(user[email])")
    }
    

    等价于执行SQL语句:

    update users set email=replace(email,'foxmail','qq') where id == 1
    SELECT * FROM users where name='究极死胖兽'
    

    执行结果:

    Update:id: 1, name: Optional("究极死胖兽"), email: scuxiatian@qq.com
    

    删除数据

    try! db?.run(users.filter(id == rowid2).delete())
    for user in (try! db?.prepare(users))! {
        print("Delete:id: \(user[id]), name: \(user[name]), email: \(user[email])")
    }
    

    等价于执行SQL语句:

    delete from users where id = 2
    SELECT * FROM users
    

    执行结果(只剩下第一条记录):

    Delete:id: 1, name: Optional("究极死胖兽"), email: scuxiatian@foxmail.com
    

    深入学习

    这里只列出了数据库的创建和最基本的增删改查操作,如果你希望能够更加深入地学习SQLite.swift,可以前往GitHub-SQLite.swift主页

    相关文章

      网友评论

        本文标题:[快速学会Swift第三方库] SQLite.swift篇

        本文链接:https://www.haomeiwen.com/subject/ttehpftx.html