FMDB 增删改查
-
FMDB 优点:
[1] 使用起来更加面向对象,省去了很多麻烦、冗余的C语言代码
[2] 对比苹果自带的Core Data框架,更加轻量级和灵活
[3] 提供了多线程安全的数据库操作方法,有效地防止数据混乱 -
核心类
[1] FMDatabase:
一个FMDatabase对象就代表一个单独的SQLite数据库
用来执行SQL语句
[2] FMResultSet:
使用FMDatabase执行查询后的结果集
[3] FMDatabaseQueue:
用于在多线程中执行多个查询或更新,它是线程安全的
#import "FMDBModel.h"
#import "FMDB.h"
// 创建数据库
NSString *create = @"CREATE TABLE IF NOT EXISTS t_GESTURE (iPhone text NOT NULL ,password text NOT NULL)";
//delete from是删除关键字,后面是要删的表名,然后可以选择跟一个where限制,限制参考修改
NSString *delete = @"delete from t_GESTURE where iPhone = ?";
//update是修改的关键字,后面是t_GESTURE表名,set表示修改动作的关键字,set后面跟着被改的字段名及其要改的内容(要改的内容也可以是?),再后面可以加where限制,也可以不加,where后面是字段=内容的结构,内容同样可以为?
NSString *updateTable = @"update t_GESTURE set password = ? where iPhone = ?";
// 查询数据库
NSString *selectTable = @"SELECT * FROM t_GESTURE";
@interface FMDBModel ()
@property (nonatomic,strong) FMDatabase *db;
@end
@implementation FMDBModel
+(FMDBModel *)fModel{
static FMDBModel *fModel = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (!fModel) {
fModel = [[FMDBModel alloc] init];
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"FMDB.sqlite"];
FMDatabase *db = [FMDatabase databaseWithPath:path];
[db open];
NSLog(@"%@",path);
[db executeUpdate:create];
[db close];
fModel.db = db;
}
});
return fModel;
}
- (void)insert{
[self.db open];
BOOL isInsert = [self.db executeUpdate:@"insert into t_GESTURE(iphone,password) VALUES (?,?)",self.phone,self.password];
if (isInsert) {
NSLog(@"插入成功");
}
[self.db close];
}
- (void)Delete{
[self.db open];
//2、调用删除语句
BOOL isDelCharactor = [self.db executeUpdate:delete,self.phone];
if (isDelCharactor) {
NSLog(@"成功");
}
[self.db close];
}
- (void)change{
[self.db open];
//2、调用修改语句
BOOL isUpdate = [self.db executeUpdate:updateTable,self.password,self.phone];
if(isUpdate == NO)
{
NSLog(@"修改失败");
return;
}else{
NSLog(@"修改成功");
}
[self.db close];
}
- (void)query{
[self.db open];
// 查询
FMResultSet *resultSet = [self.db executeQuery:selectTable];
while ([resultSet next]) {
NSString *phone = [resultSet stringForColumn:@"iPhone"];
NSString *password = [resultSet stringForColumn:@"password"];
NSLog(@" %@ %@",phone,password);
}
[self.db close];
}
使用
// 插入
- (IBAction)ConfirmDown:(id)sender {
[FMDBModel fModel].phone = self.iPhone.text;
[FMDBModel fModel].password = self.password.text;
[[FMDBModel fModel] insert];
}
// 查询
- (IBAction)SelectDown:(id)sender {
[[FMDBModel fModel] query];
}
// 删除
- (IBAction)Delete:(id)sender {
[FMDBModel fModel].phone = self.iPhone.text;
[FMDBModel fModel].password = self.password.text;
[[FMDBModel fModel] Delete];
}
// 修改
- (IBAction)change:(id)sender {
[FMDBModel fModel].phone = self.iPhone.text;
[FMDBModel fModel].password = self.password.text;
[[FMDBModel fModel] change];
}
网友评论