FMDB数据库框架的是使用

IOS操作数据库,SQLite3和coredata是两个非常好的选择,但是对于我们这些掌握了其他数据库语言的人来说,使用这两中操作都会觉得不方便,SQLite3使用起来太复杂了,而使用coredata的时候却封装太死了,我们需要自己些自己的数据库语句,这时候,FMDB就是一个非常不错的选择

下面是FMDB的基本使用

在Main.storyboard中添加4个按钮分别是(插入 , 更新,删除 , 查询)

在ViewController中

//

//  ViewController.m

 

//

//

 

#import "ViewController.h"

#import "FMDB.h"

 

@interface ViewController ()

@property (nonatomic, strong) FMDatabase *db;

- (IBAction)insert;

- (IBAction)update;

- (IBAction)delete;

- (IBAction)query;

@end

 

@implementation ViewController

 

- (void)viewDidLoad

{

    [super viewDidLoad];

    

    // 0.获得沙盒中的数据库文件名

    NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"student.sqlite"];

    

    // 1.创建数据库实例对象

    self.db = [FMDatabase databaseWithPath:filename];

   

    // 2.打开数据库

    if ( [self.db open] ) {

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

        

        // 创表

        BOOL result = [self.db executeUpdate:@"create table if not exists t_student (id integer primary key autoincrement, name text, age integer);"];

        

        if (result) {

            NSLog(@"创表成功");

        } else {

            NSLog(@"创表失败");

        }

    } else {

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

    }

}

 

- (IBAction)insert

{

    for (int i = 0; i<40; i++) {

        NSString *name = [NSString stringWithFormat:@"rose-%d", arc4random() % 1000];

        NSNumber *age = @(arc4random() % 100 + 1);

        [self.db executeUpdate:@"insert into t_student (name, age) values (?, ?);", name, age];

    }

}

 

- (IBAction)update

{

    [self.db executeUpdate:@"update t_student set age = ? where name = ?;", @20, @"jack"];

}

 

- (IBAction)delete

{

    

}

 

- (IBAction)query

{

    // 1.查询数据

    FMResultSet *rs = [self.db executeQuery:@"select * from t_student where age > ?;", @50];

    

    // 2.遍历结果集

    while (rs.next) {

        int ID = [rs intForColumn:@"id"];

        NSString *name = [rs stringForColumn:@"name"];

        int age = [rs intForColumn:@"age"];

        

        NSLog(@"%d %@ %d", ID, name, age);

    }

}

@end

 

posted @ 2014-11-03 11:44  我知道是菜鸟  阅读(154)  评论(0编辑  收藏  举报