iOS FMDB操作sqlite数据库

来源:互联网 发布:免费空间域名 编辑:程序博客网 时间:2024/04/30 06:59
一、简单说明
1.什么是FMDB
FMDB是iOS平台的SQLite数据库框架
FMDB以OC的方式封装了SQLite的C语言API

2.FMDB的优点

使用起来更加面向对象,省去了很多麻烦、冗余的C语言代码
对比苹果自带的Core Data框架,更加轻量级和灵活
提供了多线程安全的数据库操作方法,有效地防止数据混乱

3.FMDB的github地址

https://github.com/ccgus/fmdb

二、核心类

FMDB有三个主要的类
(1)FMDatabase
一个FMDatabase对象就代表一个单独的SQLite数据库
用来执行SQL语句
(2)FMResultSet

使用FMDatabase执行查询后的结果集
(3)FMDatabaseQueue
用于在多线程中执行多个查询或更新,它是线程安全的

三、打开数据库

通过指定SQLite数据库文件路径来创建FMDatabase对象
FMDatabase *db = [FMDatabase databaseWithPath:path];
if (![db open]) {
    NSLog(@"数据库打开失败!");
}
文件路径有三种情况
(1)具体文件路径
  如果不存在会自动创建
(2)空字符串@""
  会在临时目录创建一个空的数据库
  当FMDatabase连接关闭时,数据库文件也被删除
(3)nil
  会创建一个内存中临时数据库,当FMDatabase连接关闭时,数据库会被销毁

四、执行更新

在FMDB中,除查询以外的所有操作,都称为“更新”
create、drop、insert、update、delete等
使用executeUpdate:方法执行更新
- (BOOL)executeUpdate:(NSString*)sql, ...
- (BOOL)executeUpdateWithFormat:(NSString*)format, ...
- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments
示例
[db executeUpdate:@"UPDATE t_student SET age = ? WHERE name = ?;", @20, @"Jack"]

五、执行查询

查询方法
- (FMResultSet *)executeQuery:(NSString*)sql, ...
- (FMResultSet *)executeQueryWithFormat:(NSString*)format, ...
- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments
示例
// 查询数据
FMResultSet *rs = [db executeQuery:@"SELECT * FROM t_student"];
// 遍历结果集
while ([rs next]) {
    NSString *name = [rs stringForColumn:@"name"];
    int age = [rs intForColumn:@"age"];
    double score = [rs doubleForColumn:@"score"];

}

六、实战

(1)首先将github下载的fmdb文件夹中的文件添加到项目中,并添加libsqlite3.tbd的库引用,如下图


如果没有添加libsqlite3.tbd的话,会报如下错误


主要代码如下

////  ViewController.m//  FMDBDemo////  Created by 555chy on 6/22/16.//  Copyright © 2016 555chy. All rights reserved.//#import "ViewController.h"#import "fmdb/FMDB.h"#import "fmdb/FMDatabaseAdditions.h"@interface ViewController ()@property FMDatabase *db;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.        /*    typedef NS_ENUM(NSUInteger, NSSearchPathDirectory) {        NSApplicationDirectory = 1,             // supported applications (Applications)        NSDemoApplicationDirectory,             // unsupported applications, demonstration versions (Demos)        NSDeveloperApplicationDirectory,        // developer applications (Developer/Applications). DEPRECATED - there is no one single Developer directory.        NSAdminApplicationDirectory,            // system and network administration applications (Administration)        NSLibraryDirectory,                     // various documentation, support, and configuration files, resources (Library)        NSDeveloperDirectory,                   // developer resources (Developer) DEPRECATED - there is no one single Developer directory.        NSUserDirectory,                        // user home directories (Users)        NSDocumentationDirectory,               // documentation (Documentation)        NSDocumentDirectory,                    // documents (Documents)        NSCoreServiceDirectory,                 // location of CoreServices directory (System/Library/CoreServices)        NSAutosavedInformationDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 11,   // location of autosaved documents (Documents/Autosaved)        NSDesktopDirectory = 12,                // location of user's desktop        NSCachesDirectory = 13,                 // location of discardable cache files (Library/Caches)        NSApplicationSupportDirectory = 14,     // location of application support files (plug-ins, etc) (Library/Application Support)        NSDownloadsDirectory NS_ENUM_AVAILABLE(10_5, 2_0) = 15,              // location of the user's "Downloads" directory        NSInputMethodsDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 16,           // input methods (Library/Input Methods)        NSMoviesDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 17,                 // location of user's Movies directory (~/Movies)        NSMusicDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 18,                  // location of user's Music directory (~/Music)        NSPicturesDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 19,               // location of user's Pictures directory (~/Pictures)        NSPrinterDescriptionDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 20,     // location of system's PPDs directory (Library/Printers/PPDs)        NSSharedPublicDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 21,           // location of user's Public sharing directory (~/Public)        NSPreferencePanesDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 22,        // location of the PreferencePanes directory for use with System Preferences (Library/PreferencePanes)        NSApplicationScriptsDirectory NS_ENUM_AVAILABLE(10_8, NA) = 23,      // location of the user scripts folder for the calling application (~/Library/Application Scripts/code-signing-id)        NSItemReplacementDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 99,    // For use with NSFileManager's URLForDirectory:inDomain:appropriateForURL:create:error:        NSAllApplicationsDirectory = 100,       // all directories where applications can occur        NSAllLibrariesDirectory = 101,          // all directories where resources can occur        NSTrashDirectory NS_ENUM_AVAILABLE(10_8, NA) = 102                   // location of Trash directory    };    NSSearchPathForDirectoriesInDomains一般情况下只会获得到一个目录,为了兼容多个的情况,所以返回数组    */    NSString *parentPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];    NSString *dbPath = [parentPath stringByAppendingPathComponent:@"person.sqlite"];    /*     文件路径有3种情况     (1)具体文件路径(如果不存在会自动创建)     (2)空字符串@“”(会在临时目录创建一个空的数据库,当FMDatabase连接关闭时,数据库文件也被删除)     (3)nil(会创建一个内存中临时数据库,当FMDatabase连接关闭时。数据库也会被销毁)     */    FMDatabase *db = [FMDatabase databaseWithPath:dbPath];    if([db open]) {        NSLog(@"database open success");        /*         sqlite中的基本数据类型         (1)NULL,值是NULL         (2)INTEGER,值是有符号整形,根据值的大小以1,2,3,4,5,6或8字节存放         (3)REAL,值是浮点型值,以8字节IEEE浮点数存放         (4)TEXT,值是文本字符串,使用数据库编码(UTF-8,UTF-16BE或者UTF-16LE)存放         (5)BLOB,值是一个数据块,完全按照输入存放         */        bool result = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS PersonTable (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL, money float NOT NULL);"];        if(result) {            NSLog(@"create table success");        } else {            NSLog(@"create table fail");        }    } else {        NSLog(@"database open fail");    }    self.db = db;}-(void)insert {    for(int i=0; i<3; i++) {        NSString *name = [NSString stringWithFormat:@"chy_%d", arc4random_uniform(100)];        int age = arc4random_uniform(100);        float money = arc4random_uniform(100)/10.0f;        BOOL result;        //@()是将变量转化为id类型        result = [self.db executeUpdate:@"INSERT INTO PersonTable (name, age, money) VALUES (?,?,?);", name, @(age), @(money)];        NSLog(@"insert method 1 %@", result?@"success":@"fail");        result = [self.db executeUpdate:@"INSERT INTO PersonTable (name, age, money) VALUES (?,?,?);" withArgumentsInArray:@[name, @(age), @(money)]];        NSLog(@"insert method 2 %@", result?@"success":@"fail");        result = [self.db executeUpdateWithFormat:@"INSERT INTO PersonTable (name, age, money) VALUES (%@,%d,%f);", name, age, money];        NSLog(@"insert method 3 %@", result?@"success":@"fail");    }}-(void)delete {    /*     在FMDB中,除查询以外的所有炒作,都称为“更新”     create、drop、insert、update、delete等     */    BOOL result;    result = [self.db executeUpdate:@"DELETE FROM PersonTable;"];    NSLog(@"delete %@", result?@"success":@"fail");    result = [self.db executeUpdate:@"DROP TABLE IF EXISTS PersonTable;"];    NSLog(@"drop %@", result?@"success":@"fail");}-(void)query {    int count = [self.db intForQuery:@"SELECT count(*) FROM PersonTable"];    NSLog(@"query count = %d", count);    FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM PersonTable"];    while([resultSet next]) {        int ID = [resultSet intForColumn:@"id"];        NSString *name = [resultSet stringForColumn:@"name"];        int age = [resultSet intForColumn:@"age"];        double money = [resultSet doubleForColumn:@"money"];        NSLog(@"query %d,%@,%d,%lf", ID, name, age, money);    }}/* touch的响应链。首先,接收touch事件的必须是用户可交互的View,也就是userInteractionEnabled属性必须是yes 事件传递的规则是:如果上层的view截获事件,那么这个view下面的view就接收不到事件,否则触摸事件就会逐层往下传递 */-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {    [self insert];    [self query];    [self delete];}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end


七、运行结果



0 0
原创粉丝点击