1.什么是FMDB?
FMDB是iOS平台下SQLite数据库,只不过它是OC方式封装了C语言的SQLite语句,使用起来更加面向对象
2.FMDB的优点:1.使用起来更加面向对象; 2.对比苹果自带的 Core Data 数据管理工具更加的轻量级,更加的灵活,而且FMDB支持跨平台; 3.提供多线程下的数据安全保护机制,有效地防止数据混乱
3.FMDM中重要的类:
FMDBDataBase: 它代表一个数据库对象,(我们需要创建数据库对象时就使用这个类)
FMDBDataBaseQueue: 它提供多线程下执行查找删除,或者更新的数据安全保护
FMResultSet: 用来存储sql语句执行结果的集(我们执行完sql语句后得到的结果都在这个类的对象中)
ViewController.m
#import "FMDB.h" #import "Person.h" #import "DetailViewController.h" @interface ViewController () @property(nonatomic,retain)FMDatabase *db; @property(nonatomic,retain)NSMutableArray *dataArray;//存储查询到的所有Person对象 @end @implementation ViewController - (void)dealloc { self.db = nil; self.dataArray = nil; [super dealloc]; } - (NSMutableArray *)dataArray{ if (_dataArray == nil) { self.dataArray = [NSMutableArray arrayWithCapacity:0]; } return [[_dataArray retain]autorelease]; }
- (void)viewDidLoad { [super viewDidLoad]; //获取Documents文件夹路径 NSString *urlString = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]; //在Documents文件夹里创建数据库文件 db.sqlite NSString *dbPath = [urlString stringByAppendingPathComponent:@"db.sqlite"]; //创建数据库对象 //参数:数据库的路径 //执行结束后并没有帮我们生成数据库文件,只是帮我们创建了数据库对象 FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; NSLog(@"%@",NSHomeDirectory()); //代开数据库 //open操作才帮我们真正的创建数据库文件,且如果已经打开,直接返回YES,此时可以直接使用,如果打开失败会打印报错信息 BOOL isOpen = [db open]; if (isOpen) { NSLog(@"打开成功"); //创建表格 //executeUpdate 除了查询之外,其他数据创建表格,插入数据、删除数据都是用这个方法 //blob 二进制流 相当于oc的NSData BOOL isCreat = [db executeUpdate:@"create table if not exists Person(id integer primary key autoincrement,name text,gender text,age integer,photo blob)"]; NSLog(@"%@",isCreat ? @"建表成功":@"建表失败"); }else{ NSLog(@"打开失败"); } //给属性赋值 self.db = db; NSLog(@"%@",NSHomeDirectory()); }
插入:
- (IBAction)insert:(UIButton *)sender { Person *p = [[Person alloc]initWithName:@"郭美美" gender:@"女" age:20 photo:[UIImage imageNamed:@"3.gif"]]; //将图片转化成NSData对象 NSData *data = UIImagePNGRepresentation(p.photo); //@(p.age)参数必须是对象类型的才能使用 //插入操作 BOOL isInsert = [self.db executeUpdate:@"insert into Person(name,gender,age,photo)values(?,?,?,?)",p.name,p.gender,@(p.age),data]; NSLog(@"%@",isInsert ? @"插入成功":@"插入失败"); }
删除:
- (IBAction)delete:(UIButton *)sender { //根据条件删除 BOOL result = [self.db executeUpdate:@"delete from Person where id = ?",@3]; NSLog(@"%@",result ? @"删除成功":@"删除失败"); //删除全部表格内容 // BOOL isResult1 = [self.db executeUpdate:@"delete from Person"]; //删除表格 // BOOL isResult2 = [self.db executeUpdate:@"drop table Person"]; }
更新:
- (IBAction)update:(UIButton *)sender { BOOL isUpdate = [self.db executeUpdate:@"update Person set gender = ? where id = ?",@"男",@4]; NSLog(@"%@",isUpdate ? @"更新成功":@"更新失败"); }
查询:
- (IBAction)select:(UIButton *)sender { //查询全部 FMResultSet *set = [self.db executeQuery:@"select * from Person"]; //按条件查询 // FMResultSet *set = [self.db executeQuery:@"select *from Person where name = ?",@"郭美美"]; self.dataArray = [NSMutableArray arrayWithCapacity:0]; //循环取出表中的数据 //[set next] 判断写一行是否有数据 while ([set next]) { //取出每一个字段对应的数据 NSInteger ID = [set intForColumn:@"id"];//取出id字段下的数据 NSString *name = [set stringForColumn:@"name"];//取出name字段下的数据 NSString *gender = [set stringForColumn:@"gender"];//取出gender字段下的数据 NSInteger age = [set intForColumn:@"age"];//取出age字段下的数据 NSData *data = [set dataForColumn:@"photo"];//取出photo字段下的数据 //创建model类 //将二进制流转成图片 UIImage *image = [UIImage imageWithData:data]; Person *p = [[Person alloc]initWithName:name gender:gender age:age photo: image]; p.ID = ID; [self.dataArray addObject:p]; [p release]; } }
为了展现效果,我们push到下个页面查看效果:
需要准备一个自定义cell、UIViewController界面和model类
传值使用:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ //获取segue起始端的视图控制器对象 ViewController *rootVC = [segue sourceViewController]; //通过segue完成跳转的时候会触发这个方法,在跳转之前触发,一般用来传值 //获取push过去后的视图控制器对象 DetailViewController *detailVC = [segue destinationViewController]; //属性传值 detailVC.dataSource = rootVC.dataArray; }
DetailViewController.h @interface DetailViewController : UITableViewController @property(nonatomic,retain)NSMutableArray *dataSource;//属性传值使用 @end DetailViewController.m #import "DetailViewController.h" #import "Person.h" #import "PersonCell.h" #define kPersonCell @"personcell" @interface DetailViewController () @end @implementation DetailViewController - (void)dealloc { self.dataSource = nil; [super dealloc]; } - (void)viewDidLoad { [super viewDidLoad]; } #pragma mark - Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return self.dataSource.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { PersonCell *cell = [tableView dequeueReusableCellWithIdentifier:kPersonCell forIndexPath:indexPath]; //建立model类 Person *person = self.dataSource[indexPath.row]; //调用cell赋值的方法 [cell assginValues:person]; return cell; }
准备一个自定义cell:通过storyBoard实现;
布局如下:
PersonCell.h #import <UIKit/UIKit.h> @class Person; @interface PersonCell : UITableViewCell @property (retain, nonatomic) IBOutlet UILabel *nameLabel; @property (retain, nonatomic) IBOutlet UILabel *genderLabel; @property (retain, nonatomic) IBOutlet UILabel *ageLabel; @property (retain, nonatomic) IBOutlet UIImageView *photoView; @property (retain, nonatomic) IBOutlet UILabel *IDLabel; //写一个赋值方式 - (void)assginValues : (Person *)person; @end //================================================= PersonCell.m #import "PersonCell.h" #import "Person.h" @implementation PersonCell - (void)awakeFromNib { // Initialization code } //写一个赋值方式 - (void)assginValues : (Person *)person{ self.nameLabel.text = person.name; self.genderLabel.text = person.gender; self.ageLabel.text = [NSString stringWithFormat:@"%ld",person.age]; self.photoView.image = person.photo; self.IDLabel.text = [NSString stringWithFormat:@"%ld",person.ID]; } - (void)dealloc { [_nameLabel release]; [_genderLabel release]; [_ageLabel release]; [_photoView release]; [_IDLabel release]; [super dealloc]; } @end
准备一个model类:
Person.h #import <Foundation/Foundation.h> @class UIImage; @interface Person : NSObject @property(nonatomic,copy)NSString *name,*gender; @property(nonatomic)NSInteger age,ID;//基本数据类型可以省略内存修饰符assign,因为默认使用的就是assign @property(nonatomic,retain)UIImage *photo; //自定义初始化方法 - (id)initWithName : (NSString *)name gender : (NSString *)gender age : (NSInteger)age photo : (UIImage *)photo; @end //============================= Person.m #import "Person.h" #import <UIKit/UIKit.h> @implementation Person - (void)dealloc { self.name = nil; self.gender = nil; self.photo = nil; [super dealloc]; } //自定义初始化方法 - (id)initWithName : (NSString *)name gender : (NSString *)gender age : (NSInteger)age photo : (UIImage *)photo{ if (self = [super init]) { self.name = name; self.gender = gender; self.age = age; self.photo = photo; } return self; } - (NSString *)description { return [NSString stringWithFormat:@"%@ %@ %ld %@", self.name,self.gender,self.age,self.photo]; } @end
大概效果不能展示全部(仅供参考):
==============================
第三方FMDB下载:http://pan.baidu.com/s/1ntMo3ZN