[翻译] FMDB

图片 1

图片 2

FMDB

https://github.com/ccgus/fmdb

This is an Objective-C wrapper around SQLite: http://sqlite.org/

这是对 SQLite
的封装:http://sqlite.org/

Read the SQLite FAQ:

http://www.sqlite.org/faq.html

Since FMDB is built on top of SQLite, you’re going to want to read this
page top to bottom at least once. And while you’re there, make sure to
bookmark the SQLite Documentation
page: http://www.sqlite.org/docs.html

因为 FMDB 建立在 SQLite
之上,所以,你足足应当把 SQLite 文档看1回。看的时候,将
http://www.sqlite.org/docs.html 网站加多到你的浏览器书签中呢。

FMDB Class Reference:

http://ccgus.github.io/fmdb/html/index.html

Automatic Reference Counting (ARC) or Manual Memory Management?

You can use either style in your Cocoa project. FMDB Will figure out
which you are using at compile time and do the right thing.

FMDB 支持 ARC 与 非ARC 。

Usage

There are three main classes in FMDB:

FMDB 包蕴了 三 个重大的类:

  1. FMDatabase – Represents a single SQLite database. Used for
    executing SQL statements.
  2. FMResultSet – Represents the results of executing a query on
    an FMDatabase.
  3. FMDatabaseQueue – If you’re wanting to perform queries and updates
    on multiple threads, you’ll want to use this class. It’s described
    in the “Thread Safety” section below.
  4. FMDatabase – 代表了单壹的二个 SQLite
    数据库。用来施行 SQL 语句的。
  5. FMResultSet – 在 FMDatabase
    上实践了查询操作后出示的结果。
  6. FMDatabaseQueue –
    固然你想在差别的线程中还要实行查询和换代操作,你会用到那么些类。在最上边有对其的叙述。

Database Creation

An FMDatabase is created with a path to a SQLite database file. This
path can be one of these three:

因此给定2个 SQLite 数据库文件的门道来成立FMDatabase,那个文件路径可由上边 三 种办法提供:

  1. A file system path. The file does not have to exist on disk. If it
    does not exist, it is created for you.
  2. An empty string (@""). An empty database is created at a temporary
    location. This database is deleted with the FMDatabase connection
    is closed.
  3. NULL. An in-memory database is created. This database will be
    destroyed with the FMDatabaseconnection is closed.
  4. 3个系统文件路径,这一个文件路线不确定供给存在,纵然不设有,它会自行为你创立。
  5. 四个空的字符串
    @“”,它会为你创立3个权且的数据库文件。当 FMDatabase
    关闭后,这么些数据库就会被删去掉。
  6. 万1参数为 NULL
    ,那就会在内存中创建一个数据库,当 FMDatabase
    关闭后,那一个数据库就会被删除掉。

(For more information on temporary and in-memory databases, read the
sqlite documentation on the
subject:http://www.sqlite.org/inmemorydb.html)

FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];

Opening

Before you can interact with the database, it must be opened. Opening
fails if there are insufficient resources or permissions to open and/or
create the database.

在您能利用数据库在此以前,你必须先开垦它。假若系统财富不足,恐怕您未有权限展开也许创建数据库都会促成展开失利。

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

Executing Updates(实践更新)

Any sort of SQL statement which is not a SELECT statement qualifies as
an update. This
includes CREATEUPDATEINSERTALTERCOMMITBEGINDETACHDELETEDROPENDEXPLAINVACUUM,
and REPLACEstatements (plus many more). Basically, if your SQL
statement does not begin with SELECT, it is an update statement.

别的 SQL
语句,假如不是 SELECT 语句都会被当做是一个 updata
操作。
包含 CREATEUPDATEINSERTALTERCOMMITBEGINDETACHDELETEDROPENDEXPLAINVACUUM,
以及 REPLACE。所以请注意,如果你的 SQL 语句不是以 SELECT 开始的,那是一个更新操作哦。

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.

执行更新操作会再次回到一个 BOOL 值。YES
代表更新成功,NO
表示出现了好几错误。你能够调用 -lastErrorMessage 和 -lastErrorCode 方法来寻找错误的信息。

Executing Queries(实施查询)

SELECT statement is a query and is executed via one of
the -executeQuery... methods.

查询语句 SELECT 通过 -executeQuery..
中的一些主意来得以落成。

Executing queries returns an FMResultSet object if successful,
and nil upon failure. Like executing updates, there is a variant that
accepts an NSError ** parameter. Otherwise you should use
the -lastErrorMessageand -lastErrorCode methods to determine why a
query failed.

查询成功会回去3个 FMResultSet
对象,退步再次回到 nil。与实行更新操作同样,有二个变量来收纳一个 NSError
参数。当然,你也能够应用 -lastErrorMessage 和 -lastErrorCode
方法来检测为啥查询退步。

In order to iterate through the results of your query, you use
while() loop. You also need to “step” from one record to the other.
With FMDB, the easiest way to do that is like this:

为了能迭代检索处全体你的询问结果,你能够采取while() 循环。你需求使用 “step” 来从一条记下跳到别的一条记下。在 FMDB
个中,下边呈现的正是最简便易行的办法。

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

You must always invoke -[FMResultSet next] before attempting to access
the values returned in a query, even if you’re only expecting one:

您不能不平日调用方法 -[FMResultSet next] ,哪怕你只是查找一条记录。

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

FMResultSet has many methods to retrieve data in an appropriate
format:

FMResultSet
有不少格局来同盟数据格式:

  • intForColumn:
  • longForColumn:
  • longLongIntForColumn:
  • boolForColumn:
  • doubleForColumn:
  • stringForColumn:
  • dateForColumn:
  • dataForColumn:
  • dataNoCopyForColumn:
  • UTF8StringForColumnName:
  • objectForColumnName:

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.

下面的每2个主意中都有二个 {type}ForColumnIndex:自己的版本,用来匹配数据,基于查询结果中的记录。

Typically, there’s no need to -close an FMResultSet yourself, since
that happens when either the result set is deallocated, or the parent
database is closed.

进一步令人瞩目,你不用本人关闭 FMResultSet
。当父数据库关闭,可能是结果集被屏弃,它会活动关闭。

Closing(关闭)

When you have finished executing queries and updates on the database,
you should -close the FMDatabaseconnection so that SQLite will
relinquish any resources it has acquired during the course of its
operation.

当您早就实行了询问,更新了数据库,你应该使用
-close 来关闭数据库的总是,让 SQLite
释放你实施这几个操作的财富而升高功能。

[db close];

Transactions(事务)

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

FMDatabase 能够提交一个政工,通过调用
begin/end 事务语句。

Data Sanitization(数据处理)

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:

当你提供一条 SQL 语句给 FMDB
时,你不要从来给语句中的变量附上值。你应该使用专门的学问的 SQLite
绑定的语法规则:

INSERT INTO myTable VALUES (?, ?, ?)

The ? character is recognized by SQLite as a placeholder for a value
to be inserted. The execution methods all accept a variable number of
arguments (or a representation of those arguments, such as
an NSArrayNSDictionary, or a va_list), which are properly
escaped for you.

?会被识别成3个就要被替换的值。全体的的试行方式都承受不相同类其余变量(包含
NSArrayNSDictionary 大概三个 va_list),你会喜欢的。

Alternatively, you may use named parameters syntax:

用作挑选,你也能够运用明着参数的语法规则:

INSERT INTO myTable VALUES (:id, :name, :value)

The parameters must start with a colon. SQLite itself supports other
characters, but internally the Dictionary keys are prefixed with a
colon, do not include the colon in your dictionary keys.

参数在此以前务必抬高冒号。 SQLite
本身辅助很各样字符,然而 OC 中字典对象的前缀便是冒号,于是,不要在你的字典 key
值前包罗冒号。

NSDictionary *argsDict = [NSDictionary dictionaryWithObjectsAndKeys:@"My Name", @"name", nil];
[db executeUpdate:@"INSERT INTO myTable (name) VALUES (:name)" withParameterDictionary:argsDict];

Thus, you SHOULD NOT do this (or anything like this):

就此,你不要这么子写(恐怕类似那样子的):

[db executeUpdate:[NSString stringWithFormat:@"INSERT INTO myTable VALUES (%@)", @"this has \" lots of ' bizarre \" quotes '"]];

Instead, you SHOULD do:

您应当那样子写:

[db executeUpdate:@"INSERT INTO myTable VALUES (?)", @"this has \" lots of ' bizarre \" quotes '"];

All arguments provided to the -executeUpdate: method (or any of the
variants that accept a va_list as a parameter) must be objects. The
following will not work (and will result in a crash):

抱有提需要-executeUpdate:方法的参数必须是贰个目的。上面包车型客车写法是荒唐的,会招致崩溃。

[db executeUpdate:@"INSERT INTO myTable VALUES (?)", 42];

The proper way to insert a number is to box it in an NSNumber object:

插入一个数字类型的,要求运用 NSNumber
对象:

[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:42]];

Alternatively, you can use the -execute*WithFormat: variant to
use NSString-style substitution:

用作一项采取,你能够采纳-exexute*WithFormat:来交付 NSString 方式的口舌:

[db executeUpdateWithFormat:@"INSERT INTO myTable VALUES (%d)", 42];

Internally, the -execute*WithFormat: methods are properly boxing
things for you. The following percent modifiers are
recognized: %@%c%s%d%D%i%u%U%hi%hu%qi%qu%f%g%ld%lu%lld,
and %llu. Using a modifier other than those will have unpredictable
results. If, for some reason, you need the % character to appear in
your SQL statement, you should use %%.

本质上,-excute*WithFormat:方法也是三个?的措施。下边包车型地铁百分号的艺术是可以被识别的: %@%c%s%d%D%i%u%U%hi%hu%qi%qu%f%g%ld%lu%lld,
和 %llu。你使用了其他修饰语而不是这些会导致预料不到的结果。由于某些原因,你需要使用 % 出现在你的 SQL 语句中,你应该使用 %%。

Using FMDatabaseQueue and Thread Safety.(使用数据库队列以及线程安全)

Using a single instance of FMDatabase from multiple threads at once is a
bad idea. It has always been OK to make a FMDatabase object per
thread
. Just don’t share a single instance across threads, and
definitely not across multiple threads at the same time. Bad things will
eventually happen and you’ll eventually get something to crash, or maybe
get an exception, or maybe meteorites will fall out of the sky and hit
your Mac Pro. This would suck.

使用3个数据库的单例,用二十多线程来管理是很古板的。日常,分裂的线程管理贰个不等的
FMDatabase 对象是高枕而卧的。请不要创立数据库单例,并在不相同的线程中走访,假设实际不行,也并非让差异的线程同时做客这1个数据库对象。假诺你持之以恒那样做,那不时就会现出有的无缘无故的倒台,格外,只怕从天而降的陨石砸坏你的苹果Computer,别这么干哦。

So don’t instantiate a single FMDatabase object and use it across
multiple threads.

为此,不要创制贰个 FMDatabase
单例对象,然后在分化的线程中走访。

Instead, use FMDatabaseQueue. It’s your friend and it’s here to help.
Here’s how to use it:

您能够行使
FMDatabaseQueue,线程安全就靠它了:

First, make your queue.

首先,创制你的queue。

FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath];

Then use it like so:

接下来这么用:

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

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

An easy way to wrap things up in a transaction can be done like this:

对此多条查询语句事务的提交,能够这么做:

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

    if (whoopsSomethingWrongHappened) {
        *rollback = YES;
        return;
    }
    // etc…
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]];
}];

FMDatabaseQueue will run the blocks on a serialized queue (hence the
name of the class). So if you call FMDatabaseQueue’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.

FMDatabaseQueue
运转在2个串行队列此中。所以,当您在不一致的线程中调用了 FMDatabaseQueue
方法,他们将会被连串试行。那种管理格局,分歧线程间不会互相苦恼,各个线程都很happy^_^。

Note: The calls to FMDatabaseQueue’s methods are blocking. So even
though you are passing along blocks, they will not be run on another
thread.

只顾:调用 FMDatabaseQueue 方法是3个block 。就算你在 block 中使用了 block,它也不会在别的线程中运作。

Making custom sqlite functions, based on blocks.(定制 sqlite 函数,基于 blocks)

You can do this! For an example, look for “makeFunctionNamed:” in main.m

您可以定制哦!你在 main.m
文件中看看吧。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

网站地图xml地图