IOS Fmdb Official use of document G-C-D for improved performance (translation)

Source: Internet
Author: User
Tags modifiers

Since Fmdb is built on SQLite, you should at least read this article from beginning to end.
In the meantime, add the SQLite document page http://www.sqlite.org/docs.html to your bookmarks.
Automatic reference count (APC) or manual memory management?

Either way, Fmdb will know which one you are using when compiling, and then handle it accordingly.
How to use

Fmdb has three main classes

The fmdatabase– represents a separate SQLite database. The command used to perform sqlite.
fmresultset– indicates that the result set Fmdatabase executes the query
fmdatabasequeue– You should use this class if you want to execute multiple queries or updates in multiple threads. This is thread-safe.

Database creation

When you create a Fmdatabase object, the parameter is the SQLite database file path. The path can be one of the following three:
The file path. The file path does not need to be real, and is created automatically if it does not exist.
An empty string (@ ""). Indicates that an empty database is created in the temp directory, and the file is deleted when the fmdatabase link is closed.
Null. An intrinsic database is created. Similarly, when the Fmdatabase connection is closed, the data is destroyed.
(If you need to take a closer look at the staging database or the intrinsic database, Continue reading: http://www.sqlite.org/inmemorydb.html)


Fmdatabase *db = [fmdatabase databasewithpath:@ "/tmp/tmp.db"];

Open Database

The database must be open before interacting with the database. Failure to open or create a database can cause open failures if resources or permissions are insufficient.


if (![ DB Open]) {
[DB release];
Return
}

Perform the update

All commands that are not select commands are treated as updates. This includes CREATE, UPDATE, Insert,alter,
COMMIT, BEGIN, DETACH, DELETE, DROP, END, EXPLAIN, VACUUM, and REPLACE (etc.).
Simply put, a command that does not start with a select is an update command.

Performs an update that returns a bool value. Yes indicates successful execution, otherwise it indicates that there are errors.
You can call the-lasterrormessage and-lasterrorcode methods to get more information.
Execute Query

The Select command is the query, and the method to execute the query begins with-excutequery.
When the query is executed, the error returns nil if the Fmresultset object is successfully returned. Equivalent to performing the update,
Supports the use of the nserror** parameter. You can also use-lasterrorcode and-lasterrormessage to learn about error messages.
In order to traverse the query results, you can use the while loop. You also need to know how to jump to the next record. Using Fmdb, it's easy to implement, like this:


Fmresultset *s = [db executequery:@ "select * from myTable"];
while ([s next]) {
Retrieve values for each record
}

You must always call-[fmresultset next] before you access the query return value, even you only want a record:



Fmresultset *s = [db executequery:@ "select COUNT (*) from myTable"];
if ([s next]) {
int totalcount = [s intforcolumnindex:0];
}

Fmresultset provides a number of ways to get the values in the desired format:

Intforcolumn:
Longforcolumn:
Longlongintforcolumn:
Boolforcolumn:
Doubleforcolumn:
Stringforcolumn:
Dataforcolumn:
Datanocopyforcolumn:
Utf8stringforcolumnindex:
Objectforcolumn:

These methods also include the method {Type}forcolumnindex, where the parameter is the index of the column of the query result set.

You do not need to call [Fmresultset Close] to close the result set, which is automatically closed when a new result set is generated, or when its database is closed.
Close the database

When you are finished using the database, you should-close to close the database connection to release the resources that SQLite uses.

[DB close];

Transaction

Fmdatabase is a support transaction.
Data cleansing (data formatting)

Before inserting data using Fmdb, you should not take the time to review your data. You can use the standard SQLite data binding syntax.

INSERT into MyTable VALUES (?,?,?)

SQLite will recognize "?" as an input point character, and such execution will accept a mutable parameter (or other parameters, such as Nsarray, Nsdictionary, or va_list, etc.) that will be correctly escaped for you.
You can also choose to use named parameter syntax.

INSERT into MyTable VALUES (: ID,: Name,: Value)

Parameter names must begin with an impostor. SQLite natively supports other characters when the internal implementation of Dictionary key is the beginning of a colon. Note that your Nsdictionary key does not contain a colon.


Nsdictionary *argsdict = [nsdictionary dictionarywithobjectsandkeys:@ "My name", @ "name", Nil];
[DB executeupdate:@ INSERT into myTable (name) VALUES (: Name) "Withparameterdictionary:argsdict";

Moreover, the code cannot write like this (why?) Think about it. )


[DB executeupdate:@ "INSERT into MyTable VALUES (?)", @ "this have \" lots of ' bizarre \ "Quotes '"];

You should:


[DB executeupdate:@ INSERT into MyTable VALUES (?) "@" This have "lots of ' bizarre" quotes ' "];

Supplied to-executeupdate: The parameter of the method must be an object. Just like the following code does not work, and it can cause a crash.


[DB executeupdate:@ INSERT into MyTable VALUES (?) ", 42];

It's a good idea to pack numbers into NSNumber objects.


[DB executeupdate:@ INSERT into MyTable VALUES (?) ", [NSNumber numberwithint:42]];

Alternatively, you can use-execute*withformat:, which is the parameter of the NSString style


[DB executeupdatewithformat:@ INSERT into myTable VALUES (%d) ", 42];

-execute*withformat: The internal implementation of the method will help you encapsulate the data, the following modifiers are available:%@,%c,%s,%d,%d,
%i,%u,%u,%hi,%hu,%qi,%qu,%f,%g,%ld,%lu,%lld, and%llu. Otherwise, modifiers can cause unpredictable results.
In some cases, you need to use the% character in the SQL statement, you should use percent.
Using Fmdatabasequeue and Thread safety

It is unwise to use one Fmdatabase instance in multiple threads at the same time. Now you can create a Fmdatabase object for each thread.
Do not let multiple threads share the same instance, it cannot be used concurrently in multiple threads. If this happens, bad things happen all the time, and the program crashes from time to time.
Or report an anomaly, or the meteorite will fall off the sky and hit your Mac Pro. In short, it collapsed.
Therefore, do not initialize the Fmdatabase object and then use it in multiple threads.
Please use Fmdatabasequeue, it is your friend and will help you. Here's how to use it:
Create the queue first.
Fmdatabasequeue *queue = [Fmdatabasequeue Databasequeuewithpath:apath];
This is used.


[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]) {
...
}
}];

Like this, it's easy to wrap a simple task into a transaction:


[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 backstage will build a serialized g-c-d queues and executes the blocks you pass to the g-c-d queue. This means that you invoke the calling method from multiple threads at the same time,
GDC also executes in the order of the blocks it receives. No one can quarrel to whose feet everyone is happy.

IOS Fmdb Official use of document G-C-D for improved performance (translation) (RPM)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.