iOS-FMDB使用教程

2,656 阅读2分钟

一、FMDB简介

  1. SQLite,是一款轻型数据库,是一个C语言库,实现了一个一个小型、快速、高可靠性。SQLite文件格式是稳定的、跨平台、向后兼容的。
  2. FMDB是将sqlite封装处理的

二、FMDB常用类

  1. FMDatabase:一个单一的SQLite数据库,用于执行SQL语句。SQL语句学习链接
  2. FMResultSet:执行查询一个FMDatabase结果集
  3. FMDatabaseQueue:在多个线程来执行查询和更新会使用这个类

三、FMDB集成

  1. Cocoapdos集成
  • 初始化Podfile文件
pod init
  • 编辑Podfile,添加FMDB
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'MyApp' do
    # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
    use_frameworks!

    # Pods for MyApp2

    pod 'FMDB'
    # pod 'FMDB/FTS'   # FMDB with FTS
    # pod 'FMDB/standalone'   # FMDB with latest SQLite amalgamation source
    # pod 'FMDB/standalone/FTS'   # FMDB with latest SQLite amalgamation source and FTS
    # pod 'FMDB/SQLCipher'   # FMDB with SQLCipher
end

  • 安装FMDB
 pod install
  1. Carthage安装
  • 保证你的Carthage版本最新,使用命令行终端导航到你的项目主目录,执行以下的命令:
$ echo ' github "ccgus/fmdb" ' > ./Cartfile
$ carthage update

3.Swift Package Manager安装

.package(
    name: "FMDB", 
    url: "https://github.com/ccgus/fmdb", 
    .upToNextMinor(from: "2.7.7")),
    
.product(name: "FMDB", package: "FMDB")

四:FMDB使用

  1. 数据库创建,我在这里使用单例来做FMDB的增删改查的操作,如下图:
  • FMDBManager初始化,以及数据库初始化

+ (instancetype)shareInstance{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        _instance = [[FMDBManager alloc]init];
        
    });
    return _instance;
}

///初始化
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initDataBase];
    }
    return self;
}

///初始化数据库
- (void)initDataBase{
    
    ///library 路径
    NSString *libPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];
    ///数据库路径
    NSString *dbPath = [libPath stringByAppendingString:@"/user.db"];
    
    ///创建数据库
    _db = [FMDatabase databaseWithPath:dbPath];
    
    ///打开数据库
    BOOL isOpen = [_db open];
    
    if (!isOpen) {
        NSLog(@"数据库打开失败");
    } else {
        
        ///创建学生表
        NSString *sql = @"CREATE TABLE IF NOT EXISTS Student (id INTEGER PRIMARY KEY AUTOINCREMENT,name Text,userID text, className text, age text , grade text)";
        BOOL result = [_db executeUpdate:sql];
        if (result) {
            NSLog(@"创建数据库成功 %@",dbPath);
        }
        [_db close];
    }
}

2.常用的数据库操作

  • (新增一条记录)
- (void)addStudent:(Student *)student{
    
    [_db open];
    BOOL result = [_db executeQuery:@"INSERT INTO Student (name,userID,className,age,grade) values(?,?,?,?,?)",student.name,student.userID,student.className,student.age,student.grade];
    
    if (result) {
        NSLog(@"插入成功");
    } else {
        NSLog(@"插入失败");
    }
    [self.db close];
    
}

  • (删除一条记录)
    [self.db open];
    FMResultSet *result = [self.db executeQuery:@"DELETE FROM Student WHERE id = ?",ID];
    if (result) {
        NSLog(@"删除成功");
    }
    [self.db close];

  • (查询一条记录)
- (NSArray *)searchStudent:(NSString *)name{
    
    [self.db open];
    NSMutableArray *studentArr = [NSMutableArray array];
    FMResultSet *result = [self.db executeQuery:@"SELECT * FROM Student WHERE name = ?", name];
    while ([result next]) {
        Student *s = [[Student alloc]init];
        s.ID = [[result stringForColumn:@"id"] integerValue];
        s.name = [result stringForColumn:@"name"];
        s.className = [result stringForColumn:@"className"];
        s.grade = [result stringForColumn:@"grade"];
        s.userID = [result stringForColumn:@"userID"];
        s.age = [result stringForColumn:@"age"];
        [studentArr addObject:s];
    }
    
    return [studentArr mutableCopy];;
    
}
  • (查询所有记录)
- (NSArray *)getAllStudentList{
    
    [self.db open];
    NSMutableArray *studentArr = [NSMutableArray array];
    FMResultSet *result = [self.db executeQuery:@"SELECT * FROM Student"];
    while ([result next]) {
        Student *s = [[Student alloc]init];
        s.ID = [[result stringForColumn:@"id"] integerValue];
        s.name = [result stringForColumn:@"name"];
        s.className = [result stringForColumn:@"className"];
        s.grade = [result stringForColumn:@"grade"];
        s.userID = [result stringForColumn:@"userID"];
        s.age = [result stringForColumn:@"age"];
        [studentArr addObject:s];
    }
    
    return [studentArr mutableCopy];;
}

  • (修改数据库记录)
- (void)updateStudentGrade:(Student *)student{
    
    [self.db open];
    FMResultSet *result = [self.db executeQuery:@"UPDATE Student SET name = ? WHERE id = ?",student.grade,student.ID];
    if (result) {
        NSLog(@"更新成功");
    }
    [self.db close];
    
}

demo传送门