标签:
简介:
FMDB是基于SQlite3的封装一个第三方的OC库,操作起来更加简单,性能比Coredata更加高。
1.使用示例:
class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. SQLiteManager.shareManager().openDB("hjq.sqlite") return true } }
2.创建数据库并建表
import UIKit class SQLiteManager: NSObject { /// 单例
private static let manager: SQLiteManager = SQLiteManager()
class func shareManager() -> SQLiteManager { return manager }
var dbQueue: FMDatabaseQueue? /** * 打开数据库 */ func openDB(DBName: String) { // 1.根据传入的数据库名称拼接数据库路径 let path = DBName.docDir() print(path) // 2.创建数据库对象 // 注意: 如果是使用FMDatabaseQueue创建数据库对象, 那么就不用打开数据库 dbQueue = FMDatabaseQueue(path: path) // 4.创建表 creatTable() }
private func creatTable() { // 1.编写SQL语句 let sql = "CREATE TABLE IF NOT EXISTS T_Person( \n" + "id INTEGER PRIMARY KEY AUTOINCREMENT, \n" + "name TEXT, \n" + "age INTEGER \n" + "); \n" // 2.执行SQL语句 dbQueue!.inDatabase { (db) -> Void in db.executeUpdate(sql, withArgumentsInArray: nil) } } }
3.插入数据
// 1.定义SQL语句 let sql = "INSERT OR REPLACE INTO T_Status" + "(statusId, statusText, userId)" + "VALUES" + "(?, ?, ?);" // 2.执行SQL语句(用事务)
SQLiteManager.shareManager().dbQueue?.inTransaction({ (db, rollback) -> Void in for dict in statuses { let statusId = dict["id"]! // JSON -> 二进制 -> 字符串 let data = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted) let statusText = String(data: data, encoding: NSUTF8StringEncoding)! print(statusText) if !db.executeUpdate(sql, statusId, statusText, userId) { // 如果插入数据失败, 就回滚 rollback.memory = true } } })
4.查找数据
// 1.定义SQL语句 var sql = "SELECT * FROM T_Status \n" if since_id > 0 { sql += "WHERE statusId > \(since_id) \n" }else if max_id > 0 { sql += "WHERE statusId < \(max_id) \n" } sql += "ORDER BY statusId DESC \n" sql += "LIMIT 20; \n" // 2.执行SQL语句 SQLiteManager.shareManager().dbQueue?.inDatabase({ (db) -> Void in // 2.1查询数据 // 返回字典数组的原因:通过网络获取返回的也是字典数组, // 让本地和网络返回的数据类型保持一致, 以便于我们后期处理 var statuses = [[String: AnyObject]]() if let res = db.executeQuery(sql, withArgumentsInArray: nil) { // 2.2遍历取出查询到的数据 while res.next() { // 1.取出数据库存储的一条微博字符串 let dictStr = res.stringForColumn("statusText") as String // 2.将微博字符串转换为微博字典 let data = dictStr.dataUsingEncoding(NSUTF8StringEncoding)! let dict = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String: AnyObject] statuses.append(dict) } // 3.返回数据 finished(statuses) } // 3.返回数据 finished(statuses) })
5.删除和更新
// 1.定义SQL语句 let sql = "DELETE FROM T_Status WHERE createDate <= ‘\(dateStr)‘;" // 2.执行SQL语句 SQLiteManager.shareManager().dbQueue?.inDatabase({ (db) -> Void in db.executeUpdate(sql, withArgumentsInArray: nil) })
附:
String分类获取文件目录
import UIKit extension String{ /** 将当前字符串拼接到cache目录后面 */ func cacheDir() -> String{ let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString return path.stringByAppendingPathComponent((self as NSString).lastPathComponent) } /** 将当前字符串拼接到doc目录后面 */ func docDir() -> String { let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString return path.stringByAppendingPathComponent((self as NSString).lastPathComponent) } /** 将当前字符串拼接到tmp目录后面 */ func tmpDir() -> String { let path = NSTemporaryDirectory() as NSString return path.stringByAppendingPathComponent((self as NSString).lastPathComponent) } }
标签:
原文地址:http://www.cnblogs.com/HJQ2016/p/5797711.html