FMDB
全称FMDatabase,是一个用Objective-C写的sqlite封装
下载
可以通过github下载源码包,复制src/fmdb/
下所有文件到项目目录下
也可以通过CocoaPods,添加pod 'FMDB'
到配置文件中
代码
在Swift项目中添加Objective-C代码,会提示添加Bridgging-Header
在Bridgging-Header.h中添加#include "FMDB.h"
就像写C的头文件那样
然后Swift里就可以用FMDB的所有类了
获取DB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
class func getDb() -> FMDatabase { let filemgr = NSFileManager.defaultManager() let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let docsDir = dirPaths[0] as! String //数据库路径 var databasePath = docsDir.stringByAppendingPathComponent("travel.db") //如果文件不存在则创建 if !filemgr.fileExistsAtPath(databasePath) { let db = FMDatabase(path: databasePath) if db == nil { println("Error: \(db.lastErrorMessage())") } if db.open() { let sql_stmt = "CREATE TABLE IF NOT EXISTS FAVORITE (TITLE TEXT PRIMARY KEY, BOOKURL TEXT, HEADIMAGE TEXT, TEXT TEXT)" if !db.executeStatements(sql_stmt) { println("Error: \(db.lastErrorMessage())") } db.close() } else { println("Error: \(db.lastErrorMessage())") } } let resDb = FMDatabase(path: databasePath) return resDb } |
添加数据
|
var db:FMDatabase = self.getDb() db.open() db.executeUpdate("INSERT INTO FAVORITE(TITLE,BOOKURL,HEADIMAGE,TEXT)VALUES(?,?,?,?)", withArgumentsInArray: [title,bookUrl,headImage,text]) db.close() |
删除数据
|
var db:FMDatabase = self.getDb() db.open() db.executeUpdate("DELETE FROM FAVORITE WHERE TITLE = ?", withArgumentsInArray: [title]) db.close() |
查找数据
|
var db = DB.getDb() db.open() let rs:FMResultSet = db.executeQuery("SELECT * FROM FAVORITE", withArgumentsInArray: []) while(rs.next()) { var fd = FavoriteData() fd.title = rs.stringForColumn("TITLE")! fd.headImage = rs.stringForColumn("HEADIMAGE")! fd.bookUrl = rs.stringForColumn("BOOKURL")! fd.text = rs.stringForColumn("TEXT")! list.append(fd) } db.close() |
Enjoy it!
找回了一点写后端的感觉,呕吼吼吼