您的位置:首页 > 其它

FMDB的简单使用

2015-07-07 16:55 357 查看
//创建数据库,并连接

-(void)createdata

{

   

    NSArray *doucumentDirectory=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *file=[doucumentDirectory objectAtIndex:0];

    NSString *dafile=[file stringByAppendingPathComponent:@"db.sqlite"];

    

    if ([[NSFileManager defaultManager]fileExistsAtPath:dafile])

    {

        NSLog(@"数据库已存在");

    }

    db=[FMDatabase databaseWithPath:dafile];

        

    if (!db)

    {

        NSLog(@"数据库创建不成功");

    }

   else

   { if([db open])

    {

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

        FMResultSet *
set = [db executeQuery:[NSString stringWithFormat:@"select
count(*) from sqlite_master where type ='table' and name = '%@'",kUserTableName]];

        [set next];

        NSInteger count = [set intForColumnIndex:0];

        

        BOOL existTable = count;

        

        if (existTable)

        {

            NSLog(@"数据表已存在,请重新添加表");

            return;}

        else

        {

            NSString *createtable=@"CREATE
TABLE user (uid INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL, name text, interest text)";

            [db executeUpdate:createtable];}

    }

    }

}

//插入数据

-(void)insertdata:(NSArray *)arguments

{

    if ([db open])

    {

        [db executeUpdate:@"INSERT
INTO user(name, interest) VALUES(?,?) "withArgumentsInArray:arguments];

            }

}

//查询所有数据

-(NSMutableArray *)selectall

{

   

    NSMutableArray *array=[[NSMutableArray alloc]initWithCapacity:100];

    

    if ([db open])

    {

        NSString *sql=@"select
* from user where name=? or interest=?";

        FMResultSet *qureyresult=[db executeQuery:sql,@"333",@"111"];

        

        while ([qureyresult next])

        {

            NSInteger uid=[qureyresult intForColumn:@"uid"];

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

            NSString *inserest=[qureyresult stringForColumn:@"interest"];

            

            NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];

            

            [dic setValue:[NSString stringWithFormat:@"%d",uid]forKey:@"keyuid"];

            [dic setValue:name forKey:@"keyname"];

            [dic setValue:inserest forKey:@"keyinserest"];

            [array addObject:dic];

            

        }

        

    }

    return array;

}

//修改数据

-(void)mergerwithname:(NSString *)name withinterest:(NSString *)interest  anduid:(NSNumber*)uid

{

    if ([db open])

    {

        [db executeUpdate:@"UPDATE
user SET name=?,interest=? WHERE uid=? ",name,interest,uid];

    }

}

//删除数据

-(void)deletedata

{

    if ([db open])

    {

        [db executeUpdate:@"delete  from
user where name=?",[NSStringstringWithFormat:@"%@",@"eee"]];

    }

}

数据库基本就是更新和查询

除了select,db executeQuery:;其他都是更新db executeUpdate:传参数时可用db executeUpdate:withArgumentsInArray:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: