fmdb realizes the function of adding, deleting, modifying and querying sqlite database (Part 1)

Some data persistence operations are required in many places in mobile development, such as writing some data directly into the sandbox, saving it into preferences, archiving, etc. However, sometimes it is necessary to store some things with a slightly larger amount of data locally. For example, when using a third-party ring letter for IM development, we need to save user information to the mobile terminal, so we use sqlite, which is used in mobile development. Often used embedded database.

Introduction to FMDB

If we use the native method to operate the database, it will involve a lot of C-voice APIs, which is very inconvenient for developers who are used to object-oriented, so fmdb encapsulates it.
There are three main classes
in fmdb: 1. FMDatabase: used to execute sql written by developers
2. FMResultSet: to save the results of queries executed by
FMDatabase 3. FMDatabaseQueue: This class is thread-safe, if you want to use it in multiple threads The database should use this class

Use FMDatabase to operate database

1. Create a global database instance and instantiate it

// 懒加载创建数据库实例
- (FMDatabase *)db{
    if (!_db) {
        // 获取数据库创建路径
        NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"user.sqlite"];
        // 创建数据库
        _db = [FMDatabase databaseWithPath:filePath];
    }
    return _db;
}

2. Create the corresponding table. In this case, the userInfo table is created. The fields in the table are the primary key id, userid, name, age, sex, height, and weight 7 fields

// 创建表
- (BOOL)createTable{
    BOOL result;
    // 打开数据库,创建表
    if ([self.db open]) {
        result = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS userInfo(id integer PRIMARY KEY, userid text NOT NULL, name text NOT NULL, age integer, sex integer, height integer, weight integer);"];
    }
    return result;
}

3. Insert data, pass in the dictionary, and the dictionary stores the information of a user

// 插入数据
- (BOOL)inserUserInfoWithDict:(NSDictionary *)userDict{
    BOOL result;
    if ([self.db open]) {
        result = [self.db executeUpdateWithFormat:@"INSERT INTO userInfo(userid,name,age,sex,height,weight) VALUES(%@,%@,%ld,%ld,%ld,%ld)",userDict[@"userid"], userDict[@"name"], [userDict[@"age"] integerValue], [userDict[@"sex"] integerValue], [userDict[@"height"] integerValue], [userDict[@"weight"] integerValue]];
    }
    [self.db close];
    return result;
}

4. Query the corresponding user information according to the corresponding userid

// 查询用户信息,注意:即使查询出来的用户只有一个也必须调用[resultSet next]方法获取查询出来的数据
- (NSMutableArray *)queryUserInfoWithUserid:(NSString *)userid{
    NSMutableArray *userArr = [NSMutableArray array];
    if ([self.db open]) {
        FMResultSet *resultSet = [self.db executeQueryWithFormat:@"SELECT * FROM userInfo WHERE userid=%@", userid];
        while ([resultSet next]) {
            NSString *name = [resultSet stringForColumn:@"name"] ? : @"";
            NSInteger age = [resultSet intForColumn:@"age"];
            NSInteger sex = [resultSet intForColumn:@"sex"];
            NSInteger height = [resultSet intForColumn:@"height"];
            NSInteger weight = [resultSet intForColumn:@"weight"];
            NSDictionary *userDict = @{@"userid":userid, @"name":name, @"age":@(age), @"sex":@(sex), @"height":@(height), @"weight":@(weight)};
            [userArr addObject:userDict];
        }
    }
    [self.db close];
    return userArr;
}

5. Modify the personal information of the corresponding userid user

// 修改用户信息
- (BOOL)updateUserInfo:(NSDictionary *)userDict userid:(NSString *)userid{
    BOOL result;
    NSString *name = userDict[@"name"] ? : @"";
    NSInteger age = [userDict[@"age"] integerValue];
    NSInteger sex = [userDict[@"sex"] integerValue];
    NSInteger height = [userDict[@"height"] integerValue];
    NSInteger weight = [userDict[@"weight"] integerValue];
    if ([self.db open]) {
        NSString *sq = [NSString stringWithFormat:@"UPDATE userInfo SET name='%@', age='%ld', sex='%ld', height='%ld', weight='%ld' WHERE userid='%@'", name, age, sex, height, weight, userid];
        result = [self.db executeUpdate:sq];
    }
    [self.db close];
    return result;
}

6. Delete the user corresponding to the userid

// 删除用户信息
- (BOOL)deleteUserInfoWithId:(NSString *)userid{
    BOOL result;
    if ([self.db open]) {
        NSString *sq = [NSString stringWithFormat:@"delete from userInfo where userid='%@'",userid];
        result = [self.db executeUpdate:sq];
    }
    [self.db close];
    return result;
}

end

The above is the method of using FMDatabase to operate the sqlite database, which can realize the function of adding, deleting, modifying and querying the database. The next article will introduce the use of FMDatabaseQueue to solve the problem of crash caused by multi-threaded access to the database

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326029189&siteId=291194637