安裝cocopods。http://my.oschina.net/u/2418942/blog/508913。sql
安裝 pod "FMDB/SQLCipher"。若是安裝有問題,能夠先對cocopods進行update一下。數據庫
修改FMDatabase文件。添加一個宏定義,修改2個方法。添加的代碼用_標出。把帶_的代碼刪除,便可恢復。工具
#define DB_SECRETKEY @"HPSQLDatabase"atom
- (BOOL)open {加密
if (_db) {spa
return YES;.net
}3d
int err = sqlite3_open([self sqlitePath], &_db );orm
if(err != SQLITE_OK) {sqlite
NSLog(@"error opening!: %d", err);
return NO;
}else if (err == SQLITE_OK)
{
[self setKey:DB_SECRETKEY];
}
if (_maxBusyRetryTimeInterval > 0.0) {
// set the handler
[self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval];
}
return YES;
}
- (BOOL)openWithFlags:(int)flags {
if (_db) {
return YES;
}
int err = sqlite3_open_v2([self sqlitePath], &_db, flags, NULL /* Name of VFS module to use */);
if(err != SQLITE_OK) {
NSLog(@"error opening!: %d", err);
return NO;
} else if (err == SQLITE_OK) {
[self setKey:DB_SECRETKEY];
}
if (_maxBusyRetryTimeInterval > 0.0) {
// set the handler
[self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval];
}
return YES;
}
4. 創建sql語句文件。databasefile.sql
CREATE TABLE IF NOT EXISTS "databaseName" (
"did" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"name" TEXT,
"createTime" TEXT
)
5. 創建SQLManager文件。SQLiteManager.h和SQLiteManager.m文件
+ (instancetype)sharedSQLiteManager {
static SQLiteManager* manager;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[SQLiteManager alloc] init];
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
path = [path stringByAppendingPathComponent:@"databaseName.db"];
NSLog(@"SQLitePath ---- %@",path);
manager.queue = [[FMDatabaseQueue alloc] initWithPath:path];
[manager creatTable];
});
return manager;
}
- (void)creatTable {
NSString* path = [[NSBundle mainBundle] pathForResource:@"databasefile.sql" ofType:nil];
NSError* error;
NSString* statement = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
if (error != nil) {
LogE(@"創表字符串錯誤 ----- %@",error);
}
[self.queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
if ([db executeUpdate:statement]) {
NSLog(@"%@創表成功",sqlStr);
}else{
LogE(@"%@創表失敗",sqlStr);
return;
}
}];
}
}
- (void)openDateBase {
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
path = [path stringByAppendingPathComponent:@"databaseName.db"];
FMDatabase *db = [FMDatabase databaseWithPath:path];
if (![db open]) {
LogE(@"數據庫打開失敗!");
}
}
- (void)closeDateBase {
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
path = [path stringByAppendingPathComponent:@"databaseName.db"];
FMDatabase *db = [FMDatabase databaseWithPath:path];
if (![db close]) {
LogE(@"數據庫關閉失敗!");
}
}
// 獲取全部信息
- (NSMutableArray *)loadAll {
[self openDateBase];
NSString* loadStatement = @"SELECT * FROM databaseName ORDER BY did ASC;";
NSMutableArray* tempArray = [NSMutableArray array];
[self.queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
FMResultSet* result = [db executeQuery:loadStatement];
while ([result next]) {
Detail* detail = [[Detail alloc] init];
detail.dId = [NSNumber numberWithInt:[result intForColumn:@"did"]];
detail.name = [result stringForColumn:@"name"];
detail.createTime = [result stringForColumn:@"createTime"];
[tempArray detail];
}
}];
[self closeDateBase];
return tempArray;
}
// 插入數據
- (void)insertData:(Detail*)detail{
[self openDateBase];
NSString* insertStatement = @"INSERT INTO databaseName (name,createTime) VALUES (?,?);";
[self.queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
if ([db executeUpdate:insertStatement withArgumentsInArray:@[detail.name,getail.createTime]]) {
NSLog(@"添加成功");
}else{
LogE(@"添加失敗");
}
}];
[self closeDateBase];
}
// 更新信息
- (void)updatedata:(Detail*)detail{
NSString* updateStatement = @"UPDATE databaseName SET name = ? WHERE did = ?;";
[self.queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
[db executeUpdate:updateStatement withArgumentsInArray:@[detail.name,detail.dId]];
}];
}
// 刪除
- (void)deleteGroup:(Detail*)detail{
NSString* deleteStatement = [NSString stringWithFormat:@"DELETE FROM databaseName WHERE did = ?;"];
[self.queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
if ([db executeUpdate:deleteStatement withArgumentsInArray:@[detail.dId]]) {
NSLog(@"刪除成功");
}else {
NSLog(@"刪除失敗");
}
}];
}
6. 在viewController調用
#import "SQLiteManager.h"
@property (strong, nonatomic) SQLiteManager *manager;
- (void)viewDidLoad {
[super viewDidLoad];
SQLiteManager *manager = [SQLiteManager sharedSQLiteManager];
self.manager = manager;
}
而後就能夠調用方法了。
7. 在本地文件夾中找到數據庫,用Navicat Premium 工具打開,會提示「file is encrypted or is not a database」。這表示你的數據庫已經加密了。(若是不作加密的那步驟,在這裏是能夠用工具打開數據庫的)。
8. 提示: 數據庫字段名字不能用group
若是沒有加密創建的數據庫,想再加密,那麼必須把原有數據庫刪除,否則會報錯。