Home FMDB刚刚好
Post
Cancel

FMDB刚刚好

A、通过Pod安装FMDB

下面是FMDB的github地址:

https://github.com/ccgus/fmdb

B、使用FMDB

1、指定路径和sqlite文件名

这里将User.sqlite文件放在缓存目录中,通过下面的方法就得到了数据库文件的路径filePath。

1
2
3
4
//缓存目录 路径
NSString * cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, true).firstObject;
//拼接sqlite文件名
NSString & filePath = [cachePath stringByAppendingPathComponent:@"User.sqlite"];

2、使用单例获取FMDB对象

1
2
//单例方法 获取FMDB对象
FMDatabase * db = [FMDatabase databaseWithPath:filePath];

3、打开数据库

1
2
3
4
5
6
7
8
- (void)open{
    bool ret = [self.db open];
    if (ret) {
        NSLog(@"数据库打开成功");
    }else{
        NSLog(@"数据库打开失败");
    }
}

4、关闭数据库

1
2
3
4
5
6
7
8
- (void)close{
    bool ret = [self.db close];
    if (ret) {
        NSLog(@"数据库关闭成功");
    }else{
        NSLog(@"数据库关闭失败");
    }
}

5、创建表

表名:

UserList

字段:

name -> string 类型

tel -> string 类型

Id -> string 类型

1
2
3
4
5
6
bool created = [self.db executeUpdate:@"CREATE TABLE UserList (name text, tel text, Id text)"];
if (created) {
    NSLog(@"创建表成功");
}else{
    NSLog(@"创建表失败");
}

6、增

1
2
3
4
5
6
7
8
9
10
11
12
13
- (void)insertNewUser:(LYUser *)user{

    [self open];

    bool insert = [self.db executeUpdate:@"INSERT INTO UserList (name, tel, Id) VALUES (?,?,?)",user.name,user.tel,user.Id];
    if (insert) {
        NSLog(@"插入成功");
    }else{
        NSLog(@"插入失败");
    }

    [self close];
}

7、删

1
2
3
4
5
6
7
8
9
10
11
12
13
- (void)deleteUser:(LYUser *)user{

    [self open];

    bool delete = [_db executeUpdate:@"DELETE FROM UserList where Id like ?",user.Id];
    if (delete) {
        NSLog(@"删除成功");
    }else{
        NSLog(@"删除失败");
    }

    [self close];
}

8、改(更新)

1
2
3
4
5
6
7
8
9
10
11
12
13
- (void)updateUser:(LYUser *)user{

    [self open];

    bool update = [_db executeUpdate:@"UPDATE UserList SET name = ? , tel = ?  where Id = ?",user.name,user.tel,user.Id];
    if (update) {
        NSLog(@"更新数据成功");
    }else{
        NSLog(@"更新数据失败");
    }

    [self close];
}

9、查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[self open];

FMResultSet * set = [self.db executeQuery:@"SELECT * FROM UserList"];

//遍历
while ([set next]) {
    LYUser * user = [[LYUser alloc]init];
    user.name = [set stringForColumn:@"name"];
    user.tel = [set stringForColumn:@"tel"];
    user.Id = [set stringForColumn:@"Id"];
    ...
}
    
[self close];

C、Demo

Demo github

https://github.com/ly918/Demos

This post is licensed under CC BY 4.0 by the author.

给Xcode添加PCH文件

iOS10之适配问题汇总