微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用SQLite.Swift实现SQLite3.0的读写

开发环境: 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

应用实例

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

参考:
- http://www.jb51.cc/article/p-cfnffpvb-bee.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐