FMDB 的使用

经常用FMDB,但是没怎么研究,正好有时间仔细看一看。怕看过的东西过段时间忘记了,所以记录一下。
FMDB GitHub:https://github.com/ccgus/fmdb

9375A8F4-6DFD-42BC-A3C6-62227307CF16.png

README.markdown中有Usage模块,就在这开始。


BAD576EE-2142-4843-8891-40192EA671E6.png

Usage下又分了几个模块:
1,Database Creation(建库)
2,Opening(打开连接)
3,Executing Updates(更新)
4,Executing Queries(查询)
5,Closing(关闭连接)
6,Transactions(事物)
7,Multiple Statements and Batch Stuff(批处理)
8,Data Sanitization(数据清理)

一:建库
通过一个SQLite数据库文件的路径创建,这条路径可以是:
(1)文件的系统路径。
(2)一个空字符串@“”。
(3)NULL。

NSString *path = [NSTemporaryDirectory()   stringByAppendingPathComponent:@"tmp.db"];
FMDatabase *db = [FMDatabase databaseWithPath:path];

临时和内存数据库的更多信息,这方面的阅读sqlite文档:http://www.sqlite.org/inmemorydb.html

二:打开连接

if (![db open]) {
    db = nil;
    return;
}

三:更新
Any sort of SQL statement which is not a SELECT statement qualifies as an update. This includes CREATE, UPDATE, INSERT, ALTER, COMMIT, BEGIN, DETACH, DELETE, DROP, END, EXPLAIN, VACUUM, and REPLACE statements (plus many more). Basically, if your SQL statement does not begin with SELECT, it is an update statement.
Executing updates returns a single value, a BOOL. A return value of YES means the update was successfully executed, and a return value of NO means that some error was encountered. You may invoke the -lastErrorMessage and -lastErrorCode methods to retrieve more information.
大概意思是除了‘SELECT’开头的SQL语句,其他都属于更新语句。更新语句的执行返回值类型为BOOL。

四:查询
executequery查询方法执行成功返回一个FMResultSet对象,在失败时返回“nil”。
遍历查询结果,就算只想得到一个结果也要始终调用-[FMResultSet next]方法。

FMResultSet *s = [db executeQuery:@"SELECT * FROM myTable"];
while ([s next]) {
    //retrieve values for each record
}

只有一个的情况这样取值

FMResultSet *s = [db executeQuery:@"SELECT COUNT(*) FROM myTable"];
if ([s next]) {
    int totalCount = [s intForColumnIndex:0];
}

Each of these methods also has a {type}ForColumnIndex: variant that is used to retrieve the data based on the position of the column in the results, as opposed to the column's name. 根据位置而不是名字检索数据。

五:关闭连接

[db close];

关闭连接,释放资源。

六:事物
FMDatabase can begin and commit a transaction by invoking one of the appropriate methods or executing a begin/end transaction statement.

七:批处理
You can use FMDatabase's executeStatements:withResultBlock: to do multiple statements in a string:

NSString *sql = @"create table bulktest1 (id integer primary key autoincrement, x text);"
                 "create table bulktest2 (id integer primary key autoincrement, y text);"
                 "create table bulktest3 (id integer primary key autoincrement, z text);"
                 "insert into bulktest1 (x) values ('XXX');"
                 "insert into bulktest2 (y) values ('YYY');"
                 "insert into bulktest3 (z) values ('ZZZ');";

success = [db executeStatements:sql];

sql = @"select count(*) as count from bulktest1;"
       "select count(*) as count from bulktest2;"
       "select count(*) as count from bulktest3;";

success = [self.db executeStatements:sql withResultBlock:^int(NSDictionary *dictionary) {
    NSInteger count = [dictionary[@"count"] integerValue];
    XCTAssertEqual(count, 1, @"expected one record for dictionary %@", dictionary);
    return 0;
}];

八:数据清理
When providing a SQL statement to FMDB, you should not attempt to "sanitize" any values before insertion. Instead, you should use the standard SQLite binding syntax:

INSERT INTO myTable VALUES (?, ?, ?, ?)

最后,又说了多线程使用FMDB “Using FMDatabaseQueue and Thread Safety”
So don't instantiate a single FMDatabase object and use it across multiple threads。Instead, use FMDatabaseQueue. Instantiate a single FMDatabaseQueue and use it across multiple threads. The FMDatabaseQueue object will synchronize and coordinate access across the multiple threads. 不要在多个线程中调用FMDB的单例。
在多线程中要使用FMDatabaseQueue。
FMDatabaseQueuewill run the blocks on a serialized queue (hence the name of the class). So if you callFMDatabaseQueue's methods from multiple threads at the same time, they will be executed in the order they are received. This way queries and updates won't step on each other's toes, and every one is happy. The calls toFMDatabaseQueue`'s methods are blocking. So even though you are passing along blocks, they will not be run on another thread.这几句话解释了FMDatabaseQueue线程安全的原因。

FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath];
[queue inDatabase:^(FMDatabase *db) {
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @1];
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @2];
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @3];

    FMResultSet *rs = [db executeQuery:@"select * from foo"];
    while ([rs next]) {
        …
    }
}];

需要用到事务的时候

[queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @1];
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @2];
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @3];

    if (whoopsSomethingWrongHappened) {
        *rollback = YES;
        return;
    }
}];

未完待续。。。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容

  • 灵犀你多大啊? 干嘛?比你大。 嗯,这点很明显,帅哥一边说一边坏笑。 你…… 你洗好了嘛?要不要我帮你擦擦背? 不...
    灵犀心理咨询室阅读 351评论 0 1
  • 人间仙境何处寻, 尘都雾霾在清晨。 咫尺天涯无所见, 还道伊人是路人。
    xueshuai阅读 156评论 3 3
  • 村东头的老太 有两个儿子三个女儿 和一所二儿子名下的老房子 用电没有单独的户头 两个儿子不相往来后 她再也没有点过灯
    那个跑路的人阅读 59评论 0 0
  • 马上就要20了,生命早在20年前从妈妈肚子里急匆匆跑出来时就开始了,可我的人生才刚刚开始,就在我前所未有的想要去做...
    瑜璠阅读 521评论 0 1
  • 一.感恩这个明媚的早晨,感恩阳光的热情,感恩你给人们带来的活力。 二.感恩父母给我的支持,感恩父母为我操心,感恩你...
    龙骁阅读 138评论 0 2