开发环境: Swift2.3 , IOS8.0+ ,XCode8.2
导入sqlite.swift
source 'https://github.com/CocoaPods/Specs.git'
platform :ios,'8.0'
use_frameworks!
target 'sql' do
pod 'sqlite.swift','~> 0.10.1'
end
@H_301_27@应用实例
// SearchHistory.swift
// 视频搜索的记录
import UIKit
import sqlite
public class SearchHistory: NSObject {
var db:Connection!
var searchTable:Table!
var searchKey:Expression<String>!
var searchId:Expression<Int64>!
override init() {
super.init()
connectAndCreate()
}
private func connectAndCreate() {
// 建立连接
do {
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0]
db = try Connection("\(path)/db.sqlite3")
searchTable = Table("videoSearchs")
searchId = Expression<Int64>("id")
searchKey = Expression<String>("searchKey")
// 尝试创建表
do {
try db.run(searchTable.create (ifNotExists:true){ t in
t.column(searchId,primaryKey: true)
t.column(searchKey,unique:true)
})
} catch {
print(error)
}
} catch {
print(error)
}
}
public func add(keyString:String) {
let insert = searchTable.insert(searchKey <- keyString)
// 由于关键词是不能重复的,所以有可能返回nil
do {
let r = try db.run(insert)
print(r)
} catch {
print(error)
}
}
public func removeAll() {
do {
try db.run(searchTable.delete())
} catch {
print(error)
}
}
public func select(limit:Int = 10) -> [String] {
var r = [String]()
do {
let list = try db.prepare(searchTable.order(searchId.desc).limit(limit))
for l in list {
let item = l[searchKey]
print(item)
r.append(item)
}
} catch {
print(error)
}
return r
}
}