swift中使用sqlite

存档…


/*-----------
 需要引入     libsqlite3.dylib       /usr/lib/libsqlite3.dylib

 在XXX-Bridging-Header.h文件中引用
 #include <sqlite3.h>
 -----------*/


import Foundation
import UIKit

extension COpaquePointer
{
    ///读值
    func toInt(index:Int32)->Int
    {
        return sqlite3_column_int(self, index).hashValue
    }
    ///读值
    func toString(index:Int32)->String
    {
        if let c = toHasEmptyString(index)
        {
            return c
        }
        return "";
    }
    ///读值
    func toDateTime(index:Int32,optionsformat:String = "yyyy-MM-dd HH:mm:ss +0000")->NSDate
    {
        return toString(index).toDate(optionsformat)
    }
    
    func toHasEmptyString(index:Int32)->String?
    {
        let chars = UnsafePointer<CChar>(sqlite3_column_text(self, index))
        if (chars == nil)
        {
            return nil;
        }
        else
        {
            return String(CString: chars, encoding: NSUTF8StringEncoding)!
        }
    }
}


class SqliteLib
{
    static var sharedInstance:SqliteLib = SqliteLib()
    var p:COpaquePointer!
    
    private init ()
    {
        var sp = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true)
        if sp.count > 0
        {
            //print(NSFileManager.defaultManager().fileExistsAtPath())
            _ = try? NSFileManager.defaultManager().createDirectoryAtPath("\(sp[0])/Database/", withIntermediateDirectories: true, attributes: nil)
            let path = "\(sp[0])/Database/Care.sqlite"
            var db:COpaquePointer = nil
            if sqlite3_open(path, &db) == SQLITE_OK
            {
                p = db
                print(path)
            }
            else
            {
                print("打开sqlite文件失败")
            }
        }
        else
        {
            print("创建sqlite文件失败")
        }
    }
    
    func close()
    {
        sqlite3_close(p)
    }
    
    ///执行读取语句 fn:读取成功时的回调方法
    func read(sql:String,fn:(COpaquePointer)->Void)->Bool
    {
        var stmt: COpaquePointer = nil
        let status = sqlite3_prepare_v2(p, sql.cStringUsingEncoding(NSUTF8StringEncoding)!,
                                        -1, &stmt, nil)
        if status == SQLITE_OK
        {
            while sqlite3_step(stmt) == SQLITE_ROW
            {
                fn(stmt)
            }
            return true
        }
        else
        {
            print("sql错误,\(status):\(sql)")
            return false
        }
    }
    
    ///执行增删改sql语句
    func exec(sql: String) -> Bool
    {
        // let stmt = COpaquePointer.open()
        let o = sqlite3_exec(p, sql.cStringUsingEncoding(NSUTF8StringEncoding)!, nil, nil, nil)
        if o != SQLITE_OK
        {
            print("exec 执行失败 返回结果为:\(o),sql语句为:\(sql)")
        }
        else
        {
            //            print("exec 执行成功 \(sql)")
        }
        return o == SQLITE_OK
    }
    
    func count(str:String)->Int
    {
        var b = -1
        self.read(str) { (stmt) -> Void in
            b = stmt.toInt(0)
        }
        return b
    }
    
    ///表是否存在
    func existsTable(name:String)->Bool
    {
        return count("select count(*) from sqlite_master where type='table' and name='\(name)'") == 1
    }
}
    原文作者:xychuu
    原文地址: https://www.jianshu.com/p/ae7d8e744fa1
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞