加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-12 19:25:29 所属栏目:百科 来源:网络整理
导读:开发环境: 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 // 视频搜索

开发环境: 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.52php.cn/article/p-cfnffpvb-bee.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读