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

前端之家收集整理的这篇文章主要介绍了使用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

原文链接:https://www.f2er.com/sqlite/198605.html

猜你在找的Sqlite相关文章