iOS,数据库的使用(FMDB库的使用和配置)

来源:互联网 发布:求购淘宝店 编辑:程序博客网 时间:2024/06/07 02:12

使用之前,需要将FMDB库拖入工程中,并配置libsqlite.tbd文件(Build Phases --> Link Binary With Libraries -->+)

<span style="font-size:18px;">#import "ViewController.h"#import "FMDatabase.h"@interface ViewController (){    FMDatabase *_database;    }@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    [self createDatabase];        [self createTable];    //    [self insertData];        [self selectData];        [self updataData];        [self deleteData];}- (void)createDatabase{        //设置数据库的文件地址    NSString *path = [NSString stringWithFormat:@"%@/Documents/students.info",NSHomeDirectory()];        //初始化数据库    _database = [[FMDatabase alloc] initWithPath:path];        BOOL b = [_database open];//打开数据库!必须要执 [-database open],此步是为了判断是否打开    if (!b) {        NSLog(@"faild");        return;    }else{        NSLog(@"success");    }}- (void)createTable{//    structure query language 结构化查询语言//    NSString *sql = @"create table student(sid varchar(32),name varchar(32),password varchar(32),score integer)";     NSString *sql = @"create table if not exists student(sid varchar(32),name varchar(32),password varchar(32),score integer)";//    执行查询的SQL//    _database executeQuery:<#(NSString *), ...#>//    执行非查询SQL语句//    _database executeUpdate:<#(NSString *), ...#>    BOOL b = [_database executeUpdate:sql];    NSLog(@"创建表 %@",b?@"成功":@"失败");}- (void)insertData{        NSString *sid = @"001";    NSString *name = @"aaaa";    NSString *password = @"888888";    int score = 100;        NSString *sql = @"insert into student(sid,name,password,score) values(?,?,?,?)";    //插入所有的参数,都必须转化为NSString类型    BOOL b = [_database executeUpdate:sql,sid,name,password,[NSString stringWithFormat:@"%d",score]];    NSLog(@"插入数据 %@",b?@"成功":@"失败");}- (void)selectData{    NSString *sql = @"select * from student";    //FMResultSet 表示结果集,类似二维表    FMResultSet *result = [_database executeQuery:sql];    //遍历结果集中每一行    while ([result next]) {                NSString *sid = [result stringForColumn:@"sid"];        NSString *name = [result stringForColumn:@"name"];        NSString *password = [result stringForColumn:@"password"];        int score = [result intForColumn:@"score"];        NSLog(@"sid = %@ name = %@ password = %@ score = %d",sid,name,password,score);    }    }//修改数据- (void)updataData{    NSString *sql = @"update student set score=88 where name='sasa'";    BOOL b = [_database executeUpdate:sql];    NSLog(@"更新数据 %@",b?@"success":@"faild");    }- (void)deleteData{    NSString *sql = @"delete from student where name='sasa'";    BOOL b = [_database executeUpdate:sql];    NSLog(@"删除数据 %@",b?@"success":@"faild");}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end</span>
其中:createDatabase ,createTable,在创建和使用数据库的时候必须要执行的方法


0 0
原创粉丝点击