標籤:
先簡單介紹一下FMDB,FMDB是iOS平台的SQLite資料庫架構,以OC的方式封裝了SQLite的C語言API。使用起來很方便,省去了很多冗餘的C語言代碼,對比蘋果內建的Core Data架構,更加輕量級和靈活,提供了多安全執行緒的資料庫操作方法,有效地防止資料混亂。
-------------------------------------------------------------------------------------------------------------------
github地址
https://github.com/ccgus/fmdb
具體使用:
1.將FMDB匯入到你的項目中去,然後添加libsqlite3.tbd(xcode7以後的版本).
2.
#import <Foundation/Foundation.h>@interface DataBaseManager : NSObject//寫個單例+(instancetype)sharedFMDataBase;
#import "DataBaseManager.h"#import "FMDB.h"@interface DataBaseManager()@property (nonatomic,strong) FMDatabase * db;@end@implementation DataBaseManager+(instancetype)sharedFMDataBase{ static DataBaseManager*manager=nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ manager=[[DataBaseManager alloc]init]; }); return manager;}- (instancetype)init{ self = [super init]; if (self) { NSString*doc=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];//得到資料庫 NSString*filename=[doc stringByAppendingPathComponent:@"students.sqlite"]; //當資料庫檔案不存在時會自動建立一個資料庫檔案。 //判斷資料庫是否存在 if (!self.db) { //不存在建立 self.db=[FMDatabase databaseWithPath:filename]; } //為資料庫設定緩衝,提高查詢效率 [self.db setShouldCacheStatements:YES]; BOOL open=[self.db open];//測試資料庫是否開啟成功 if(open){ NSLog(@"資料庫開啟成功"); }else{ NSLog(@"資料庫開啟失敗"); } //開啟資料庫 if ([self.db open]) { if (![self.db tableExists:@"t_student"]) { //建立表 BOOL result=[self.db executeUpdate: @"CREATE TABLES t_student(id INTEGER PRIMARY KEY AUTOINCREAMENT, name TEXT, age TEXT)"]; //將字典轉成nsdata,而sql中儲存是用的blob類型 if (result) { NSLog(@"成功創表"); }else{ NSLog(@"創表失敗"); } } NSLog(@"已經有表了,不需要重新添加"); } //關閉資料庫 [self.db close]; } return self;}
對資料的基本操作:
//添加資料[self.db open]; [self.db executeUpdate:@"INSERT INTO t_student(name,age)values(?,?)",@"xiaoming",@"123"]; [self.db close];
//查詢資料 [self.db open]; FMResultSet*resultSet=[self.db executeQuery:@"select * from t_student"]; while ([resultSet next]) { int ID = [resultSet intForColumn:@"id"]; NSString *name = [resultSet stringForColumn:@"name"]; NSString* age = [resultSet stringForColumn:@"age"]; NSLog(@"%d %@ %@", ID, name, age); } [self.db close];
ios 關於FMDB的基本使用