数据库MFDB的使用

//第一步导入FMDB数据库

//第二步在Build Phasses中导入数据库:libsqlite3.tbd

//创建DataBase类,在DataBase类中创建两个基于NSObject的类对象(Tel和DataBase)

.h

@interface Tel : NSObject

@property(nonatomic,assign)NSInteger  theId;

@property(nonatomic,strong)NSString *name,*phone,*em;

@end

@interfaceDataBase :NSObject

//单例方法

+(instancetype)initData;

-(void)initSql;

-(void)addData:(Tel*)data;

-(void)update:(Tel*)data;

-(void)delData:(NSInteger)theid;

-(NSMutableArray*)showArray;

@end

.m

#import "DataBase.h"

#import "FMDatabase.h"

//创建静态变量

staticDataBase*sqlData;

static FMDatabase *db;

@implementation Tel

@end

@implementation DataBase

+(instancetype)initData{

    if(!sqlData) {

        sqlData= [DataBasenew];

    }

    return sqlData;

}

-(void)initSql{

    NSString *strPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];


    NSString*fileName = [strPathstringByAppendingString:@"filename.db"];

    db= [[FMDatabasealloc]initWithPath:fileName];


    if([dbopen]) {

        NSLog(@"打开数据库成功");

        [db executeUpdate:@"create table sql(theId integer primary key,name text,phone text,em text)"];

        [dbclose];

    }

    else{

       NSLog(@"打开数据库失败");

    }

}

-(void)addData:(Tel*)data{

    if([dbopen])

    {

        [db executeUpdate:[NSString stringWithFormat:@"insert into sql values(null,'%@','%@','%@')",data.name,data.phone,data.em]];

    }

    else

    {

        NSLog(@"添加数据失败");

    }


    [dbclose];

}

-(void)update:(Tel*)data{

    if([dbopen]) {

        [db executeUpdate:[NSString stringWithFormat:@"update sql set name ='%@',phone = '%@',em = '%@' where theId = '%ld'",data.name,data.phone,data.em,data.theId]];

    }

    else

    {

        NSLog(@"修改数据失败");

    }


    [dbclose];

}

-(void)delData:(NSInteger)theid

{

    if([dbopen]) {

        [db executeUpdate:[NSString stringWithFormat:@"delete from sql where theId = '%ld'",theid]];

    }

    else

    {

        NSLog(@"删除数据失败");

    }

    [dbclose];

}

-(NSMutableArray*)showArray{

    NSMutableArray *array = [NSMutableArray array];


    FMResultSet *set = [FMResultSet new];

    if([dbopen])

    {

       set = [db executeQuery:@"select *from sql"];

        while([setnext]) {

            Tel*t = [Telnew];

            t.theId= [setintForColumn:@"theId"];

            t.name= [setstringForColumn:@"name"];

            t.phone= [setstringForColumn:@"phone"];

            t.em= [setstringForColumn:@"em"];


            [arrayaddObject:t];

        }


    }

    else

    {

        NSLog(@"查询数据失败");

    }

    [dbclose];

    returnarray;

}

@end

//创建基于:UIView的类(TelView)

.h

@interfaceTelView :UIView

@property(nonatomic,strong)UITextField*nameTf,*phoneTf,*emTf;

@end

.m

#import "TelView.h"

@implementation TelView

-(instancetype)initWithFrame:(CGRect)frame{


    if(self= [superinitWithFrame:frame]) {

        [selfaddSubview:self.nameTf];

        [selfaddSubview:self.phoneTf];

        [selfaddSubview:self.emTf];


    }

    return self;

}

-(UITextField*)nameTf{


    if(!_nameTf) {

        _nameTf= [[UITextFieldalloc]initWithFrame:CGRectMake(0,90,self.frame.size.width,44)];


        _nameTf.placeholder = @"please you name";


        _nameTf.textAlignment = NSTextAlignmentCenter;


        _nameTf.borderStyle = UITextBorderStyleRoundedRect;

    }

    return _nameTf;

}

-(UITextField*)phoneTf{


    if(!_phoneTf) {

        _phoneTf= [[UITextFieldalloc]initWithFrame:CGRectMake(0,140,self.frame.size.width,44)];


        _phoneTf.placeholder = @"please you phone";


        _phoneTf.textAlignment = NSTextAlignmentCenter;


        _phoneTf.borderStyle = UITextBorderStyleRoundedRect;

    }

    return _phoneTf;

}

-(UITextField *)emTf{


    if(!_emTf)

    {

        _emTf= [[UITextFieldalloc]initWithFrame:CGRectMake(0,190,self.frame.size.width,44)];


        _emTf.placeholder = @"please you email";


        _emTf.textAlignment = NSTextAlignmentCenter;


        _emTf.borderStyle = UITextBorderStyleRoundedRect;

    }

    return _emTf;

}

@end

//创建导航条

//在AppDelgate.m中添加以下代码

#import "ViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {

    self.window.rootViewController =

    [[UINavigationController alloc]initWithRootViewController:[ViewController new]];

    return YES;

}

//在ViewController.h中把UIViewController 修改成:UITableViewController

.m  添加以下代码

#import "ViewController.h"

//Model

#import "DataBase.h"

//Controller

#import "SecViewController.h"

@interface ViewController ()

{

    NSMutableArray *array;

}

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];


    self.title=@"通讯录";


    UISearchBar*search = [[UISearchBaralloc]initWithFrame:CGRectMake(0,0,self.view.frame.size.width,44)];

    self.tableView.tableHeaderView = search;

    //创建右按钮

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:self action:@selector(click)];

    //设置行高

    self.tableView.rowHeight = 90;

    //初始化数组

    array = [NSMutableArray array];

}

-(void)click{


    [self.navigationController pushViewController:[SecViewController new] animated:YES];

}

//视图将要展示

-(void)viewWillAppear:(BOOL)animated

{

    [[DataBase initData]initSql];


    array = [[DataBase initData]showArray];


    [self.tableView reloadData];

}

#pragma mark -

#pragma mark UITableViewDataSource

-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section

{

    returnarray.count;

}

-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{


    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@""];

    if(!cell)

    {

        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];

    }

    Tel*t =array[indexPath.row];


    cell.textLabel.text= [NSStringstringWithFormat:@"%ld\n姓名:%@\n手机号:%@\n邮箱:%@",t.theId,t.name,t.phone,t.em];


    cell.textLabel.numberOfLines = 0;


    returncell;

}

-(void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath{


    [[DataBase initData]initSql];


    [[DataBaseinitData]delData:[array[indexPath.row]theId]];


    [arrayremoveObject:array[indexPath.row]];


    [self.tableView reloadData];

}

-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{

SecViewController *sec = [SecViewController new];

    sec.t=array[indexPath.row];

 [self.navigationController pushViewController:sec animated:YES];

}

@end

//创建SecViewController

在.h好中添加头文件和声明属性:

#import "DataBase.h"

@property(nonatomic,strong)Tel *t;

在.m文件夹中添加以下大码

//Model

#import "DataBase.h"

//View

#import "TelView.h"

@interface SecViewController ()

{

    TelView*tview;

}

@end

@implementationSecViewController

- (void)viewDidLoad {

    [super viewDidLoad];


    tview = [[TelView alloc]initWithFrame:self.view.frame];


    tview.backgroundColor = [UIColor lightGrayColor];


    self.view=tview;

    tview.nameTf.text = self.t.name;

    tview.phoneTf.text = self.t.phone;

    tview.emTf.text = self.t.em;


    if(!self.t) {

        self.title=@"添加数据";

        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(save)];

    }

    else{

        self.title=@"修改数据";

        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"修改" style:UIBarButtonItemStylePlain target:self action:@selector(change)];

    }


}

-(void)save

{

    Tel*tel = [Telnew];


    tel.name = tview.nameTf.text;

    tel.phone = tview.phoneTf.text;

    tel.em=tview.emTf.text;


    [[DataBase initData]initSql];

    [[DataBase initData]addData:tel];

    [self.navigationController popViewControllerAnimated:YES];

}

-(void)change

{

    self.t.name =tview.nameTf.text;

    self.t.phone = tview.phoneTf.text;

    self.t.em = tview.emTf.text;


    [[DataBase initData]initSql];


    [[DataBase initData]update:self.t];


    [self.navigationController popViewControllerAnimated:YES];

}

你可能感兴趣的:(数据库MFDB的使用)