ios数据存储(三)

来源:互联网 发布:ps照片水彩效果知乎 编辑:程序博客网 时间:2024/06/05 20:59
/** 数据库三个步骤: 1,打开 2,操作 3,关闭 */#import "ViewController.h"#import "FMDB.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    NSArray *pathesArr =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    NSString *path = [pathesArr firstObject];    NSString *dbPath = [path stringByAppendingPathComponent:@"sqlite.db"];    NSLog(@"%@",dbPath);    //考虑了线程安全的问题    FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:dbPath];    [queue inDatabase:^(FMDatabase *db) {        FMResultSet *set = [db executeQuery:@"select id from myTable where name = 'wangbing';"];        //遍历所得到的结果        while ([set next]) {            int int_id = [set intForColumn:@"id"];            NSLog(@"%zi",int_id);        }        //结果集需要关闭        [set close];        [db close];    }];    //3,关闭    [queue close];}//不考虑线程安全的方式来操作数据- (void)dbByDatabase{    NSArray *pathesArr =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    NSString *path = [pathesArr firstObject];    NSString *dbPath = [path stringByAppendingPathComponent:@"sqlite.db"];    NSLog(@"%@",dbPath);    //FMDatabase:数据库类    FMDatabase *database = [FMDatabase databaseWithPath:dbPath];    if ([database open]) {        //2,操作        //建表        if ([database executeUpdate:@"create table if not exists 'myTable' (id int,name varchar(255),height float, primary key (id)) ;"]) {            NSLog(@"建表成功");            //插入数据            //            if ([database executeUpdate:@"insert into myTable (id,name,height) values (1,'yhuihui',172);"]) {            //                NSLog(@"插入数据成功");            //            }            /*             //利用占位符的方式插入某条数据             if ([database executeUpdate:@"insert into myTable (id,name,height) values (?,?,?);",[NSNumber numberWithInt:3],@"wangshuo",[NSNumber numberWithFloat:178.0f]]) {             NSLog(@"插入数据成功");             }             */            /*             //删除数据             if ([database executeUpdate:@"DELETE FROM myTable WHERE id = 1;"]) {             NSLog(@"删除数据成功");             }             */            /*             if ([database executeUpdate:@"UPDATE myTable SET name = 'lixiujuan' WHERE id = 2;"]) {             NSLog(@"更新数据成功");             }             */            FMResultSet *set = [database executeQuery:@"select id from myTable where name = 'wangshuo';"];            //遍历所得到的结果            while ([set next]) {                int int_id = [set intForColumn:@"id"];                NSLog(@"%zi",int_id);            }            //结果集需要关闭            [set close];        };    }    //3,关闭    [database close];}
1 0