说明:针对的FMDB版本为2.5,未作修改。

inDatabase, inTransaction中为dispatch_sync(_queue, ^() { }操作。

_queue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL);

 

0.要使用事务,需要开启:

[self.dataBaseQueue inDatabase:^(FMDatabase *db) {

        tResult = [db executeUpdate:@"PRAGMA foreign_keys = ON"];

        if(!tResult) return ;

    }];

开启事务实质属于查询操作(待确定),不能在inTransaction:^(){}中使用。

查询操作最好使用inDataBase:^(){},更新等操作使用inTransaction:^(){}。

 

1.FMDataBase非线程安全,使用FMDataBaseQueue,如:

[self.dataBaseQueue inDatabase:^(FMDatabase *db) {

        NSString *tSql = [NSString stringWithFormat:@"SELECT * FROM %@", kDBTableUser];

        FMResultSet *tRS = [db executeQuery:tSql];

        while ([tRS next]) {

        }

    }];

 

2.FMDataBaseQueue使用事务,如:

- (BOOL)addUser:(NSDictionary *)aUser

{

    __block BOOL tResult = NO;

    [self.dataBaseQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {

        NSString *tSql = [NSString stringWithFormat:@"REPLACE INTO %@ VALUES('%@', '%@')",kDBTableUser, aUser[@"userID"], aUser[@"userName"]];

        tResult = [db executeUpdate:tSql];

        if(!tResult)

        {

            *rollback = YES;

            return ;// 退出了这个block

        }

    }];

    return tResult;

}

 

3. 使用FMDB时,若使用

 - (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments

插入修改数据,需要arguments里面的keyvalue顺序与创建表时顺序一致,否则会出现错误。(还不知道为什么,可能和column index绑定有关)

 

4.在使用sql语句时,如果使用NSString格式化字符串(stringWithFormat),最好将表名,column名使用单引号圈起来('%@')。

 

5.在插入不明字段时,使用

[tValue stringByReplacingOccurrencesOfString:@"'" withString:@"''"];

对单引号(')进行转义。

 

6.多表查询语句,如:

select * from user 

inner join bookmarks on user.userID = bookmarks.userID 

inner join history on user.userID = history.userID

where user.userGender=0 and user.userVIP = 1

将从3个表user, bookmarks, history中选取userGender==0&&userVIP ==1的所有数据,并形成一个表,字段为3个表的并集。

 

欢迎指正。

posted on 2015-09-07 09:48  梦丶想  阅读(812)  评论(0编辑  收藏  举报