The use of Fmdb in iOS development

Source: Internet
Author: User
Tags db2

The native SQLite API for iOS is quite unfriendly in use and inconvenient when used. As a result, a series of libraries to encapsulate the SQLite API, such as FMDB, Plausibledatabase, sqlitepersistentobjects, etc., FMDB (https://github.com/ccgus/ Fmdb) is a concise, easy-to-use package library, this article briefly introduces the Fmdb.

After Fmdb downloads the file, the project must import the following files and use the Libsqlite3.dylib dependency package.

The Fmdb is compatible with both arc and non-ARC projects and automatically adjusts the associated memory management code according to the engineering configuration.

Fmdb Common classes:

Fmdatabase: A single SQLite database for executing SQL statements.
Fmresultset: Executes a query with a fmdatabase result set, which is similar to the cursor on Android.
Fmdatabasequeue: This class is used when multiple threads are executing queries and updates.

Create DATABASE: db = [Fmdatabase Databasewithpath:database_path];

1, when the database file does not exist, Fmdb will create a.

2, if you pass in a parameter is empty string: @ "", then Fmdb will create the database in the temporary file directory, the database is disconnected, the database file is deleted.

3. If you pass in a parameter that is NULL, it will establish a database in memory and the database file is deleted when the database is disconnected.

Open database: [DB open];

Close database: [DB close];

Database additions and deletions and other operations: in addition to query operations, FMDB database operations are executed Executeupdate method, this method returns bool type.

To create a table:

  1. if ([db Open]) {
  2. NSString *sqlcreatetable = [NSString stringwithformat:@"CREATE TABLE IF not EXISTS '%@ ' ('%@ ' INTEGER PRIMARY KEY AUT  Oincrement, '%@ ' text, '%@ ' INTEGER, '%@ ' text) ', tablename,id,name,age,address];
  3. BOOL res = [db executeupdate:sqlcreatetable];
  4. if (!res) {
  5. NSLog (@"error when creating DB table");
  6. } Else {
  7. NSLog (@"success to creating DB table");
  8. }
  9. [DB close];
  10. }

Add Data:if ([db Open]) {

NSString *insertsql1= [NSString stringWithFormat:

@"INSERT into '%@ ' ('%@ ', '%@ ', '%@ ') VALUES ('%@ ', '%@ ', '%@ ')",

TABLENAME, NAME, age, ADDRESS, @"Zhang San", @ "@", @"Jinan"];

BOOL res = [db EXECUTEUPDATE:INSERTSQL1];

NSString *INSERTSQL2 = [NSString stringWithFormat:

@"INSERT into '%@ ' ('%@ ', '%@ ', '%@ ') VALUES ('%@ ', '%@ ', '%@ ')",

TABLENAME, NAME, age, ADDRESS, @"John Doe", @ "a",@"Jinan"];

BOOL res2 = [db EXECUTEUPDATE:INSERTSQL2];

if (!res) {

NSLog (@"error when insert DB table");

} Else {

NSLog (@"success to insert DB table");

}

[DB close];

}

To modify the data:

if ([db Open]) {

NSString *updatesql = [NSString stringWithFormat:

@"UPDATE '%@ ' SET '%@ ' = '%@ ' WHERE '%@ ' = '%@ '",

TABLENAME, age, @ "All", age, @"13"];

BOOL res = [db executeupdate:updatesql];

if (!res) {

NSLog (@"error when update db table");

} Else {

NSLog (@"Success to update DB table");

}

[DB close];

}

Delete data:

if ([db Open]) {

NSString *deletesql = [NSString stringWithFormat:

@"Delete from%@ where%@ = '%@ '",

TABLENAME, NAME, @"Zhang San"];

BOOL res = [db executeupdate:deletesql];

if (!res) {

NSLog (@"error when delete db table");

} Else {

NSLog (@"success to delete db table");

}

[DB close];

}

Database Query Operations:

The query operation uses executequery and involves Fmresultset

if ([db Open]) {

NSString * sql = [NSString stringWithFormat:

@"SELECT * from%@", TABLENAME];

Fmresultset * rs = [db Executequery:sql];

While ([Rs next]) { int Id = [Rs intforcolumn:id];

NSString * name = [Rs Stringforcolumn:name];

NSString * age = [Rs stringforcolumn:age];

NSString * address = [Rs stringforcolumn:address];

NSLog (@"id =%d, name =%@, age =%@ address =%@", ID, name, age, address);

}

[DB close];

}

Fmdb's Fmresultset provides several ways to get different types of data:

Multi-threaded database operations:

If you use a multi-threaded database in your application, you need to use Fmdatabasequeue to ensure thread safety. It is not common in the application to use a Fmdatabase object in multiple threads to manipulate the database, which can cause confusion in database data. For multi-threaded operation of database security, Fmdb uses Fmdatabasequeue, using Fmdatabasequeue is very simple, first with a database file address to the initial fmdatabasequeue, and then you can be a closure (block) Passed into the Indatabase method. Operate the database in a closure without directly participating in the management of the fmdatabase.

Fmdatabasequeue * queue = [Fmdatabasequeue Databasequeuewithpath:database_path];

dispatch_queue_t q1 = dispatch_queue_create ("queue1", NULL);

dispatch_queue_t q2 = dispatch_queue_create ("Queue2", NULL);

Dispatch_async (Q1, ^{

for (int i = 0; i < ++i) {

[Queue indatabase:^ (Fmdatabase *db2) {

NSString *insertsql1= [NSString stringWithFormat:

@"INSERT into '%@ ' ('%@ ', '%@ ', '%@ ') VALUES (?,?,?)",

TABLENAME, NAME, age, ADDRESS];

NSString * name = [NSString stringwithformat:@"Jack%d", I];

NSString * age = [NSString stringwithformat:@"%d", 10+i];

BOOL res = [DB2 EXECUTEUPDATE:INSERTSQL1, Name, age,@"Jinan"];

if (!res) {

NSLog (@"error to Inster data:%@", name);

} Else {

NSLog (@"succ to Inster Data:%@", name);

}

}];

}

});

Dispatch_async (Q2, ^{

for (int i = 0; i < ++i) {

[Queue indatabase:^ (Fmdatabase *db2) {

NSString *insertsql2= [NSString stringWithFormat:

@"INSERT into '%@ ' ('%@ ', '%@ ', '%@ ') VALUES (?,?,?)",

TABLENAME, NAME, age, ADDRESS];

NSString * name = [NSString stringwithformat:@"Lilei%d", I];

NSString * age = [NSString stringwithformat:@"%d", 10+i];

BOOL res = [DB2 executeupdate:insertsql2, Name, age,@"Beijing"];

if (!res) {

NSLog (@"error to Inster data:%@", name);

} Else {

NSLog (@"succ to Inster Data:%@", name);

}

}];

}

});

The use of Fmdb in iOS development

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.