首页 > 代码库 > FMDB----SQL----数据库
FMDB----SQL----数据库
#pragma mark -- 数库
- (void)createDatabase{
//路径
NSString *path = [NSString stringWithFormat:@"%@/Documents/maxueshan.db",NSHomeDirectory()];
//创建
_database = [[FMDatabase alloc]initWithPath:path];
//打开
[_database open];
NSLog(@"%@",path);
}
//重写析构方法 , 不能写 [super dealloc]
- (void)dealloc{
//关闭数据库
[_database close];
}
#pragma mark -- 创建表格
- (void)createTable{
NSString *sql = @"create table if not exists Student(stuName text,stuAge text, stuSex text)";
BOOL isSuccess = [_database executeUpdate:sql];
if (isSuccess) {
NSLog(@"table表格创建成功");
}else {
NSLog(@"table表格创建失败");
}
}
//增
- (void)insertDataWithArray:(NSArray *)array{
if (array.count == 0) {
//数组为空,没有模型
return;
}
//1.SQL语句 拼接
NSString *sql = @"insert into Student values(?,?,?)";
//2.遍历数组
for (StudentModel *model in array) {
//
[_database executeUpdate:sql,model.stuName,model.stuAge,model.stuSex];
}
}
//删
- (void)deleteDataWithArray:(NSArray *)array{
if (array.count == 0) {
return ;
}
NSString *sql = @"delete from Student where stuName=? and stuAge=? and stuSex=?";
for (StudentModel *model in array) {
[_database executeUpdate:sql,model.stuName,model.stuAge,model.stuSex];
}
}
//改
- (BOOL)updateDataWithSourceModle:(StudentModel *)sourceModel andNewModel:(StudentModel *)newModel{
if (sourceModel && newModel) {
//两个模型都不为空时,才执行 数据的修改
NSString *sql = @"update Student set stuName=? , set stuAge=? , set stuSex=? where stuName=? and stuAge=? and stuSex=?";
BOOL isSuccess = [_database executeUpdate:sql,newModel.stuName,newModel.stuAge,newModel.stuSex,sourceModel.stuName,sourceModel.stuAge,sourceModel.stuSex];
return isSuccess;
}
return NO;
}
//查
- (NSArray *)selectAllDatas{
//1.数组,接收模型
NSMutableArray *dataArr = [NSMutableArray array];
//2.sql 语句
NSString *sql = @"select *from Student";
//3.查询
FMResultSet *set = [_database executeQuery:sql];
//4.遍历,分装模型
while ([set next]) {
NSString *name = [set stringForColumn:@"stuName"];
NSString *age = [set stringForColumn:@"stuAge"];
NSString *sex = [set stringForColumn:@"stuSex"];
NSDictionary *dic = @{@"stuName":name,@"stuAge":age,@"stuSex":sex};
StudentModel *model = [StudentModel createModelWithDic:dic];
[dataArr addObject:model];
}
return dataArr;
}
//姓名
- (NSArray *)selectForName:(NSString *)name {
if (name.length == 0) {
return nil;
}
NSMutableArray *dataArr = [NSMutableArray array];
NSString *sql = @"select * form Student where stuName=? ";
FMResultSet *set = [_database executeQuery:sql,name];
while ([set next]) {
NSString *name = [set stringForColumn:@"stuName"];
NSString *age = [set stringForColumn:@"stuAge"];
NSString *sex = [set stringForColumn:@"stuSex"];
NSDictionary *dic = @{@"stuName":name,@"stuAge":age,@"stuSex":sex};
StudentModel *model = [StudentModel createModelWithDic:dic];
[dataArr addObject:model];
}
return dataArr;
}
FMDB----SQL----数据库