[快速學(xué)會Swift第三方庫] SQLite.swift篇

SQLite.swift 是一個使用純 Swift 語言封裝 SQLite3 的操作框架。

特性:

1?簡單的查詢和參數(shù)綁定接口
2?安全、自動類型數(shù)據(jù)訪問
3?隱式提交和回滾接口
4?開發(fā)者友好的錯誤處理和調(diào)試
5?文檔完善
6?通過廣泛測試

目錄

  • [快速學(xué)會Swift第三方庫 SQLiteswift篇]
    • [目錄]
    • [編碼之前]
      • [導(dǎo)入SQLiteswift]
      • [其他操作]
    • [鏈接數(shù)據(jù)庫]
    • [創(chuàng)建表]
    • [插入數(shù)據(jù)]
    • [查詢數(shù)據(jù)]
    • [修改數(shù)據(jù)]
    • [刪除數(shù)據(jù)]
    • [深入學(xué)習(xí)]

編碼之前

導(dǎo)入SQLite.swift

推薦使用CocoaPods進(jìn)行導(dǎo)入,CocoaPods是一個負(fù)責(zé)管理iOS項目中第三方開源庫的工具,安裝CocoaPods之后使用命令行就能輕松地對所有第三方開源庫進(jìn)行安裝和更新,而不需要每次上GitHub去下載。
CocoaPods的安裝過程傳送門:iOS 9 導(dǎo)入類庫全面詳盡過程(Ruby安裝->CocoaPods安裝->導(dǎo)入類庫)
手動下載:GitHub-SQLite.swift主頁

裝好CocoaPods后,修改Podfile文件內(nèi)容為如下:

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是我的工程名)

再執(zhí)行命令:

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

鏈接數(shù)據(jù)庫

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

創(chuàng)建表

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)
        }))

等價于執(zhí)行SQL語句:

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

插入數(shù)據(jù)

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))!

等價于執(zhí)行SQL語句:

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

查詢數(shù)據(jù)

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

等價于執(zhí)行SQL語句:

SELECT * FROM users

執(zhí)行結(jié)果:

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

條件查詢會在后面用到

修改數(shù)據(jù)

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])")
}

等價于執(zhí)行SQL語句:

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

執(zhí)行結(jié)果:

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

刪除數(shù)據(jù)

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])")
}

等價于執(zhí)行SQL語句:

delete from users where id = 2
SELECT * FROM users

執(zhí)行結(jié)果(只剩下第一條記錄):

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

深入學(xué)習(xí)

這里只列出了數(shù)據(jù)庫的創(chuàng)建和最基本的增刪改查操作,如果你希望能夠更加深入地學(xué)習(xí)SQLite.swift,可以前往GitHub-SQLite.swift主頁

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 1、通過CocoaPods安裝項目名稱項目信息 AFNetworking網(wǎng)絡(luò)請求組件 FMDB本地數(shù)據(jù)庫組件 SD...
    陽明AGI閱讀 16,003評論 3 119
  • 四年級 / 薛博文 去年冬天的一個晚上,我把頭給碰破了! 事情要從那件事說起:寫完作業(yè),我準(zhǔn)備去廁所洗一下...
    zyl林閱讀 595評論 6 13
  • 太陽很大,在黑夜里。 意識逐漸清醒了,印入眼瞳的橘黃色燈光,是一盞搖曳的吊燈。 我還記得買這盞燈燈時候,壓低了帽檐...
    名偵探夏蔡田閱讀 301評論 1 2