- 主要實(shí)現(xiàn)邏輯
通過(guò)繼承
HWFMDBModel
,在操作數(shù)據(jù)庫(kù)時(shí),內(nèi)部通過(guò)runtime
獲取模型的屬性列表,通過(guò)手動(dòng)拼接SQL
語(yǔ)句來(lái)實(shí)現(xiàn)數(shù)據(jù)的增刪改查
,廢話不多說(shuō)了直接代碼
未命名.gif
-
HWFMDBModel
介紹
/** 注意:添加必須大寫(xiě) 用于記錄添加數(shù)據(jù)id */
@property (nonatomic, assign) NSInteger ID;
/** 創(chuàng)建表 */
+ (BOOL)hw_createTableWithName:(NSString *)tableName db:(FMDatabase *)db;
/** 插入數(shù)據(jù) */
- (BOOL)hw_insertTableWithName:(NSString *)tableName db:(FMDatabase *)db;
/** 刪除數(shù)據(jù) */
- (BOOL)hw_deleteTableWithName:(NSString *)tableName db:(FMDatabase *)db;
/** 更新數(shù)據(jù) */
- (BOOL)hw_updateTableWithName:(NSString *)tableName db:(FMDatabase *)db;
/** 查詢數(shù)據(jù) */
+ (NSArray *)hw_queryTableWithName:(NSString *)tableName db:(FMDatabase *)db;
簡(jiǎn)單使用
- 首先定義模型繼承HWFMDBModel
#import <Foundation/Foundation.h>
#import "HWFMDBModel.h"
NS_ASSUME_NONNULL_BEGIN
@interface FMDBItem : HWFMDBModel
/** <#注釋#> */
@property(nonatomic, strong) NSString *name;
/** <#注釋#> */
@property(nonatomic, assign) NSInteger age;
@end
NS_ASSUME_NONNULL_END
- 在控制器中創(chuàng)建
DB
(這里用的懶加載)
@property(nonatomic, strong) FMDatabase *db;
- (FMDatabase *)db {
if (!_db) {
NSString *docuPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *dbPath = [docuPath stringByAppendingPathComponent:@"text.db"];
NSLog(@"數(shù)據(jù)庫(kù)路徑:%@",dbPath);
_db = [FMDatabase databaseWithPath:dbPath];
}
return _db;
}
- 創(chuàng)建表 鏈?zhǔn)介_(kāi)發(fā)案例
// 直接通過(guò)模型類方法創(chuàng)建模型
BOOL tag = [FMDBItem hw_createTableWithName:tableName db:self.db];
if (tag) {
NSLog(@"創(chuàng)建成功");
} else {
NSLog(@"創(chuàng)建失敗");
}
- 插入數(shù)據(jù)
FMDBItem *item = [FMDBItem new];
NSInteger num = arc4random() % 1000;
item.name = [NSString stringWithFormat:@"李含文%ld",num];
item.age = num;
BOOL tag = [item hw_insertTableWithName:tableName db:self.db];
if (tag) {
NSLog(@"插入成功");
[weakSelf loadData];
} else {
NSLog(@"插入失敗");
}
- 查詢數(shù)據(jù)
NSArray *itemArray = [FMDBItem hw_queryTableWithName:tableName db:self.db];
- 更新數(shù)據(jù)
FMDBItem *item = self.itemArray[indexPath.row];
item.name = @"李含文";
item.age = 18;
BOOL tag = [item hw_updateTableWithName:tableName db:self.db];
if (tag) {
NSLog(@"操作成功");
[self.tableView reloadData];
} else {
NSLog(@"操作失敗");
}
- 刪除數(shù)據(jù)(直接用模型刪除)
FMDBItem *item = self.itemArray[indexPath.row];
BOOL tag = [item hw_deleteTableWithName:@"text" db:self.db]; // 刪除操作
if (tag) {
NSLog(@"刪除成功");
} else {
NSLog(@"刪除失敗");
}
- 刪除表
NSString *sql = [NSString stringWithFormat:@"DROP TABLE IF EXISTS %@", tableName];
BOOL tag = [self.db executeUpdate:sql];
if (tag) {
NSLog(@"刪除成功");
} else {
NSLog(@"刪除失敗");
}
Dome
注意:本文沒(méi)有對(duì)DB
的開(kāi)啟關(guān)閉做任何操作,開(kāi)啟關(guān)閉須自行管理