FMDB使用的一点心得:数据库创建、制表、查询等以及image转换成二进制nsdata保存到数据库中

<span style="font-size:18px;">//首先,获取数据库的路径,(假设不存在,就是我们想要存储的路径),不用操心每次都创建数据库会反复,不会的,假设没有则创建,有了就不会再反复创建。
//接下来。我们要制表,首先我们先查看我们的表是否已经存在,方法在以下代码中;假设存在则跳过。不存在则创建</span>
-(void)DataBaseInit
{
    //获取Document目录下的数据库文件,没有则创建
    NSString *dbPath = [self getDBPath];
    FMDatabase *membersDB = [FMDatabase databaseWithPath:dbPath];
    if (![membersDB open]) {
        NSLog(@"open membersDB failed");
        return;
    }

    //监測数据库中我要须要的表是否已经存在
    NSString *existsSql = [NSString stringWithFormat:@"select count(name) as countNum from sqlite_master where type = 'table' and name = '%@'", @"Member" ];
    FMResultSet *rs = [membersDB executeQuery:existsSql];
    
    if ([rs next]) {
        NSInteger count = [rs intForColumn:@"countNum"];
        NSLog(@"The table count: %li", count);
        if (count == 1) {
            NSLog(@"log_keepers table is existed.");
            return;
        }
        
        NSLog(@"log_keepers is not existed.");
        //创建表
        //[membersDB executeUpdate:@"CREATE TABLE PersonList (Name text, Age integer, Sex integer,Phone text, Address text, Photo blob)"];
        [membersDB executeUpdate:@"CREATE TABLE Member (Name text, Age integer, Sex integer,Height integer, Weight integer, Photo blob)"];
    }  
    
    [rs close];
}

-(NSString *)getDBPath
{
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *DBPath = [documentPath stringByAppendingPathComponent:@"members.db"];//成员列表数据库
    return DBPath;
}


以下是数据成员的加入。只是我首先检查数据库中我要建的成员是否已经存在,避免反复加入

-(void)doneAction:(UIButton *)button
{
    //保存到数据库 membersDB
    //获取Document目录下的数据库文件。没有则创建
    NSString *dbPath = [self getDBPath];
    FMDatabase *membersDB = [FMDatabase databaseWithPath:dbPath];
    if (![membersDB open]) {
        NSLog(@"open membersDB failed");
        return;
    }
    //返回数据库中第一条满足条件的结果
    //select count(name) as countNum from sqlite_master where type = 'table' and name = '%@'", @"log_keepers
    FMResultSet *rs =[membersDB executeQuery:@"SELECT COUNT(Name) AS countNum FROM Member WHERE Name = ?
上一篇:安卓开发


下一篇:IOS DB技术方案对比