IOS-CoreData(增删改查、表关联、分页和模糊查询、多个数据库)
2016-01-27 20:27
656 查看
1>什么是CoreData
Core Data是iOS5之后才出现的一个框架,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数据库中的数据还原成OC对象。在此数据操作期间,我们不需要编写任何SQL语句,这个有点类似于著名的Hibernate持久化框架,不过功能肯定是没有Hibernate强大的。
2>CoreData的使用步骤
1.创建模型文件
2.添加实体
3.创建实体类
4.生成上下文 关联模型文件生成数据库
5.保存对象到数据库
6.从数据库获取对象
7.更新数据
8.删除数据
3>打开CoreData的SQL语句输出开关
1.打开Product,点击EditScheme...
2.点击Arguments,在ArgumentsPassed On Launch中添加2项
1> -com.apple.CoreData.SQLDebug
2> 1
一、CoreData基本使用-增删改查和表关联
三、分页查询和模糊查询
三、创建多个数据库
Core Data是iOS5之后才出现的一个框架,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数据库中的数据还原成OC对象。在此数据操作期间,我们不需要编写任何SQL语句,这个有点类似于著名的Hibernate持久化框架,不过功能肯定是没有Hibernate强大的。
2>CoreData的使用步骤
1.创建模型文件
2.添加实体
3.创建实体类
4.生成上下文 关联模型文件生成数据库
5.保存对象到数据库
6.从数据库获取对象
7.更新数据
8.删除数据
3>打开CoreData的SQL语句输出开关
1.打开Product,点击EditScheme...
2.点击Arguments,在ArgumentsPassed On Launch中添加2项
1> -com.apple.CoreData.SQLDebug
2> 1
一、CoreData基本使用-增删改查和表关联
// // ViewController.m // IOS_0121_CoreData // // Created by ma c on 16/1/21. // Copyright © 2016年 博文科技. All rights reserved. // #import "ViewController.h" #import <CoreData/CoreData.h> #import "Employee.h" #import "Department.h" @interface ViewController () @property (nonatomic, strong) NSManagedObjectContext *context; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //1.创建模型文件(相当于数据库中的表) //2.添加实体(一张表) //3.创建实体类(相当于模型) //4.生成上下文,关联模型文件生成数据库 //上下文 self.context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; //模型数据文件 NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil]; //持久化存储器 //把数据保存到一个文件,而不是内存 NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; //数据名字和路径 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *sqlitePath = [path stringByAppendingPathComponent:@"company.sqlite"]; NSLog(@"%@",sqlitePath); NSURL *url = [NSURL fileURLWithPath:sqlitePath]; [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:nil]; self.context.persistentStoreCoordinator = store; } //数据库操作ADUQ (ADD、Delete、Update、Query) #pragma mark - 添加员工 - (IBAction)addEmployee { Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context]; emp.name = @"bowen"; emp.height = @"180"; emp.birthday = [NSDate date]; //直接保存 NSError *error = nil; [self.context save:&error]; if (error) { NSLog(@"%@",error); } } #pragma mark - 查询员工 - (IBAction)searchEmployee { //1.NSFetchRequest 抓取请求对象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; //2.设置过滤条件 NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"bowen"]; request.predicate = pre; //3.排序 NSSortDescriptor *heightSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:YES]; request.sortDescriptors = @[heightSort]; //4.执行请求 NSError *error = nil; NSArray *emps = [self.context executeFetchRequest:request error:&error]; if (error) { NSLog(@"%@",error); } for (Employee *emp in emps) { NSLog(@"name:%@ height:%@ birthday:%@",emp.name, emp.height, emp.birthday); } } #pragma mark - 更新员工 - (IBAction)updateEmployee { //1.查找 //获取对象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; //设置过滤条件 NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"bowen"]; request.predicate = pre; //执行请求 NSArray *emps = [self.context executeFetchRequest:request error:nil]; //2.更新 for (Employee *emp in emps) { emp.height = @"200"; } //3.保存 [self.context save:nil]; } #pragma mark - 删除员工 - (IBAction)deleteEmployee { //1.查找 //获取对象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; //设置过滤条件 NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"bowen"]; request.predicate = pre; //执行请求 NSArray *emps = [self.context executeFetchRequest:request error:nil]; //2.删除 for (Employee *emp in emps) { [self.context deleteObject:emp]; } //3.保存 [self.context save:nil]; } #pragma mark - 表关联 - (IBAction)AddRelationship { //创建两个部门:IOS、Android Department *IOSDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:self.context]; IOSDepart.departNo = @"001"; IOSDepart.name = @"IOS"; IOSDepart.createDate = [NSDate date]; Department *AndroidDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:self.context]; AndroidDepart.departNo = @"002"; AndroidDepart.name = @"Android"; AndroidDepart.createDate = [NSDate date]; //创建两个员工:bowen1,bowen2 Employee *emp1 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context]; emp1.name = @"bowen1"; emp1.height = @"180"; emp1.birthday = [NSDate date]; emp1.depart = IOSDepart; Employee *emp2 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context]; emp2.name = @"bowen2"; emp2.height = @"180"; emp2.birthday = [NSDate date]; emp2.depart = AndroidDepart; //保存 [self.context save:nil]; } - (IBAction)searchRelationship { //读取IOS部门员工 //1.NSFetchRequest 抓取请求对象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; //2.设置过滤条件 NSPredicate *pre = [NSPredicate predicateWithFormat:@"depart.name = %@",@"IOS"]; request.predicate = pre; //3.执行请求 NSError *error = nil; NSArray *emps = [self.context executeFetchRequest:request error:&error]; if (error) { NSLog(@"%@",error); } for (Employee *emp in emps) { NSLog(@"name:%@ height:%@ birthday:%@",emp.name, emp.height, emp.birthday); } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
三、分页查询和模糊查询
// // ViewController.m // IOS_0121_CoreData // // Created by ma c on 16/1/21. // Copyright © 2016年 博文科技. All rights reserved. // #import "ViewController.h" #import <CoreData/CoreData.h> #import "Employee.h" #import "Department.h" @interface ViewController () @property (nonatomic, strong) NSManagedObjectContext *context; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //1.创建模型文件(相当于数据库中的表) //2.添加实体(一张表) //3.创建实体类(相当于模型) //4.生成上下文,关联模型文件生成数据库 //上下文 self.context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; //模型数据文件 NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil]; //持久化存储器 //把数据保存到一个文件,而不是内存 NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; //数据名字和路径 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *sqlitePath = [path stringByAppendingPathComponent:@"company.sqlite"]; NSLog(@"%@",sqlitePath); NSURL *url = [NSURL fileURLWithPath:sqlitePath]; [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:nil]; self.context.persistentStoreCoordinator = store; } //数据库操作ADUQ (ADD、Delete、Update、Query) #pragma mark - 添加员工 - (IBAction)addEmployee { for (int i = 0; i < 15; i++) { Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context]; emp.name = [NSString stringWithFormat:@"bowen%d",i]; emp.height = [NSString stringWithFormat:@"%d",180+i]; emp.birthday = [NSDate date]; } //直接保存 NSError *error = nil; [self.context save:&error]; if (error) { NSLog(@"%@",error); } } #pragma mark - 分页查询 - (IBAction)pagingAndQuerying { //1.NSFetchRequest 抓取请求对象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; //2.排序 NSSortDescriptor *heightSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:YES]; request.sortDescriptors = @[heightSort]; //3.分页查询 //分页的起始索引 request.fetchOffset = 12; //分页的条数 request.fetchLimit = 6; //4.执行请求 NSError *error = nil; NSArray *emps = [self.context executeFetchRequest:request error:&error]; if (error) { NSLog(@"%@",error); } for (Employee *emp in emps) { NSLog(@"name:%@ height:%@ birthday:%@",emp.name, emp.height, emp.birthday); } } - (IBAction)fuzzyQuery { //1.NSFetchRequest 抓取请求对象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; //2.排序 NSSortDescriptor *heightSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:YES]; request.sortDescriptors = @[heightSort]; //3.模糊查询 //名字以“bowen1”开头 //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",@"bowen1"]; //request.predicate = pre; //名字以“1”结尾 //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name ENDSWITH %@",@"1"]; //request.predicate = pre; //名字包含“wen1”结尾 //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"1"]; //request.predicate = pre; //like //名字以“1”结尾 //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"*wen14"]; //request.predicate = pre; //名字以“bowen2”开头 NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"bowen2*"]; request.predicate = pre; //4.执行请求 NSError *error = nil; NSArray *emps = [self.context executeFetchRequest:request error:&error]; if (error) { NSLog(@"%@",error); } for (Employee *emp in emps) { NSLog(@"name:%@ height:%@ birthday:%@",emp.name, emp.height, emp.birthday); } } @end
三、创建多个数据库
// // ViewController.m // IOS_0121_CoreData // // Created by ma c on 16/1/21. // Copyright © 2016年 博文科技. All rights reserved. // #import "ViewController.h" #import <CoreData/CoreData.h> #import "Employee.h" #import "Status.h" @interface ViewController () @property (nonatomic, strong) NSManagedObjectContext *companyContext; @property (nonatomic, strong) NSManagedObjectContext *weibocontext; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //一个数据库对应着一个上下文 self.companyContext = [self setupContextWithModelName:@"Company"]; self.weibocontext = [self setupContextWithModelName:@"weibo"]; } //根据模型文件返回上下文 - (NSManagedObjectContext *)setupContextWithModelName:(NSString *)modelName { //1.创建模型文件(相当于数据库中的表) //2.添加实体(一张表) //3.创建实体类(相当于模型) //4.生成上下文,关联模型文件生成数据库 //上下文 NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; //模型数据文件 //使用下面的方法,如果boundles为空,会把boundles里面所有的模型文件的表都放在一个数据库中 //NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil]; NSLog(@"%@",[[NSBundle mainBundle] bundlePath]); NSURL *modelURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"]; NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; //持久化存储器 //把数据保存到一个文件,而不是内存 NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; //数据名字和路径 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *sqlliteName = [NSString stringWithFormat:@"%@.sqllite",modelName]; NSString *sqlitePath = [path stringByAppendingPathComponent:sqlliteName]; NSLog(@"%@",sqlitePath); NSURL *url = [NSURL fileURLWithPath:sqlitePath]; [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:nil]; context.persistentStoreCoordinator = store; return context; } //数据库操作ADUQ (ADD、Delete、Update、Query) #pragma mark - 添加 - (IBAction)add { Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.companyContext]; emp.name = @"bowen"; emp.height = @"180"; emp.birthday = [NSDate date]; Status *status = [NSEntityDescription insertNewObjectForEntityForName:@"Status" inManagedObjectContext:self.weibocontext]; status.text = @"回家"; status.createDate = @"2015-01-28"; [self.companyContext save:nil]; [self.weibocontext save:nil]; } #pragma mark - 查询 - (IBAction)querying { } @end
相关文章推荐
- 在Windows上安装MongoDB
- 如何将Oracle数据库中的数据导入到hbase中 使用 Sqoop工具
- ORACLE中对版本和补丁的说明
- SQL*Loader的使用总结(三)
- MySQL 5.5 服务器变量详解(一)
- SQL Server Management Studio(SSMS)的使用与配置整理(不定期更新 2016/02/04)
- mysql查询当前用户
- oracle undo 复杂度--oracle核心技术读书笔记四
- MySQL 事务
- MySQL行级锁、表级锁、页级锁详细介绍
- Mysql程序
- MySQL数据表基本操作
- ORACLE PILE 与 SPFILE
- oracle模糊查询用法
- HBase数据库与关系型数据库的区别(取材于官方文档)
- mysql btree与hash索引的适用场景和限制
- spring-data-mongodb报错
- SQL三种分页方式
- mysql慢查询
- Oracle导出导入指定表