iOS开发~FMDB的使用

//获取沙盒路径
NSArray *filePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [filePath objectAtIndex:0];
NSLog(@"filePath:%@",filePath);
NSString *dbFilePath = [documentPath stringByAppendingPathComponent:@"db.sqlite"];

//建立数据库
FMDatabase *database = [FMDatabase databaseWithPath:dbFilePath];

//建表
//判断数据库是否已经打开,如果没有打开,提示失败
if (![self.database open]) {
    NSLog(@"数据库打开失败");
    return;
}
//为数据库设置缓存,提高查询效率
[self.database setShouldCacheStatements:YES];
//判断数据库中是否已经存在这个表,如果不存在则创建该表
BOOL result=[self.database executeUpdate:@"CREATE TABLE IF NOT EXISTS condition (condition_id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL);"];
if (result) {
    NSLog(@"创表成功");
} else {
    NSLog(@"创表失败");
}
[self getDataBaseArray];

[self.database close];


//添加
if ([self.database open]) {
    NSString *insertSql1= [NSString stringWithFormat:@"INSERT INTO 'condition' ('condition_id','name') VALUES ('1','%@')", @"交通"];
    BOOL res = [self.database executeUpdate:insertSql1];
    
    NSString *insertSql2= [NSString stringWithFormat:@"INSERT INTO 'condition' ('condition_id','name') VALUES ('2','%@')", @"教育"];
    [self.database executeUpdate:insertSql2];
    
    if (!res) {
        NSLog(@"error when insert db table");
    } else {
        NSLog(@"success to insert db table");
    }
    [self.dataBaseArray addObject:@"交通"];
    [self.dataBaseArray addObject:@"教育"];
    [self.database close];
    
}


//查询
if ([self.database open]) {
    NSString * sql = [NSString stringWithFormat:
                      @"SELECT * FROM condition"];
    FMResultSet * rs = [self.database executeQuery:sql];
    NSLog(@"rs:%@",rs);
    while ([rs next]) {
        int Id = [rs intForColumn:@"condition_id"];
        NSString * name = [rs stringForColumn:@"name"];
        NSLog(@"name = %@, id = %d", name, Id);
        [self.dataBaseArray addObject:name];
    }
    [self.database close];
}

//删除
if ([self.database open]) {
    
    NSString *deleteSql = [NSString stringWithFormat:@"delete from condition where condition_id = '%d'", (i + 1)];
    BOOL res = [self.database executeUpdate:deleteSql];
    
    if (!res) {
        NSLog(@"error when delete db table");
    } else {
        NSLog(@"success to delete db table");
    }
    [self.database close];
    
}


//修改
if ([self.database open]) {
    NSString *updateSql = [NSString stringWithFormat:@"UPDATE 'condition' SET 'name' = 'lin' WHERE 'name' = '张三'"];
    BOOL res = [self.database executeUpdate:updateSql];
    if (!res) {
        NSLog(@"error when update db table");
    } else {
        NSLog(@"success to update db table");
    }
    [self.database close];
    
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值