SQLite (http://www.sqlite.org/docs.html) is a lightweight relational database. The IOS SDK supports SQLite very early, and when used, it only needs to join Libsqlite3.dylib dependencies and introduce sqlite3.h header files. However, the native SQLite API is quite unfriendly in use and inconvenient when used. As a result, there is a series of libraries that encapsulate the SQLite API in the open source community, while Fmdb (Https://github.com/ccgus/fmdb) is a great person in the open source community.
The Fmdb is very convenient to use. Here is a simple example:
123456789 |
NSString*Docsdir=[Nssearchpathfordirectoriesindomains(NSDocumentDirectory,Nsuserdomainmask,YES)Lastobject];NSString*DBPath=[DocsdirstringByAppendingPathComponent:@ "User.sqlite"];Fmdatabase*Db=[FmdatabaseDatabasewithpath:DBPath];[DbOpen];Fmresultset*Rs=[db executequery:@ "select * from people" ];while ([rs next]) Span class= "p" >{ nslog (@ "%@%@" , [rs stringforcolumn:@ "FirstName" ], [rs stringforcolumn:@ "LastName" ); }[db Close;
|
As you can see, the database code after using Fmdb is clear and more elegant than the native API. In addition, the Fmdb is compatible with both arc and non-ARC projects and automatically adjusts the associated memory management code according to the engineering configuration.
Instructions for use
This instruction is mainly translated from Fmdb's GitHub project documentation: HTTPS://GITHUB.COM/CCGUS/FMDB
Introduction of related Documents
First clone the Fmdb from GitHub and copy the following files into your project:
123456789 |
Fmdatabase.Hfmdatabase. Mfmdatabaseadditions. Hfmdatabaseadditions. Mfmdatabasepool. Hfmdatabasepool. Mfmdatabasequeue. Hfmdatabasequeue. Mfmresultset. Hfmresultset. M
|
Set up a database
Creating a database requires only the following line, and when the file does not exist, Fmdb creates one yourself. If you pass in an empty string: @ "", Fmdb will create the database in the temporary file directory, and if the parameter you pass in is NULL, it will establish a database in memory.
1 |
FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
|
Open Database
Using the following statement, if open fails, it may be insufficient permissions or insufficient resources. Usually after you open the operation, you need to call the Close method to close the database.
1 23456< Span class= "Line-number" >78 |
if (![db open]) { // error return;}// some operation// ...[db close];
|
Perform an update operation
In addition to the select operation, the others are update operations. The update operation uses the following method, if there is an error, can be obtained in the error parameter.
1 |
-[FMDatabase executeUpdate:error:withArgumentsInArray:orVAList:]
|
Perform a query operation
An example of a query operation is shown below. Note: You need to call the next method of Fmresultset even if the result of the operation is only one row.
123456789 |
Fmresultset*S=[DbExecuteQuery:@ "SELECT * FROM MyTable"];While([SNext]) { //retrieve values for each Record}fmresultset *< span class= "n" >s = [db executequery: @ "select COUNT (*) from myTable" if ([s next]) { int totalcount = [s intforcolumnindex:0];}
|
Fmdb provides several ways to obtain different types of data:
123456789 |
intForColumn:longForColumn:longLongIntForColumn:boolForColumn:doubleForColumn:stringForColumn:dateForColumn:dataForColumn:dataNoCopyForColumn:UTF8StringForColumnIndex:objectForColumn:
|
Typically, you do not need to close fmresultset because the Fmresultset is automatically closed when the associated database is closed.
Data parameters
Typically, you can use a standard SQL statement to represent parameters that execute statements, such as the following:
1 |
INSERT INTO myTable VALUES (?, ?, ?)
|
Then, we can call the Executeupdate method to pass in the specific parameters of the referring generation, usually with variable-length parameters to be passed in, as follows:
12 |
NSString *sql = @"insert into User (name, password) values (?, ?)";[db executeUpdate:sql, user.name, user.password];
|
It should be noted here that the parameter must be a subclass of NSObject, so a basic type like int,double,bool needs to be encapsulated into the corresponding wrapper class, as follows:
1 234 |
// 错误,42不能作为参数[db executeUpdate:@"INSERT INTO myTable VALUES (?)", 42];// 正确,将42封装成 NSNumber 类[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:42]];
|
Thread Safety
If our app requires a multi-threaded database, then we need to use Fmdatabasequeue to ensure thread safety. Remember that you cannot co-fmdatabase objects in multiple threads and use them concurrently in multiple threads, and that the class itself is not thread-safe, which can cause problems with data clutter.
The
Using Fmdatabasequeue is simple, first fmdatabasequeue with a database file address, and then you can pass a closure (block) into the Indatabase method. Operate the database in a closure without directly participating in the management of the fmdatabase.
1234< Span class= "Line-number" >5678< Span class= "Line-number" >9101112< Span class= "Line-number" >13141516 171819 20212223 242526 2728 |
Created, preferably in a singleton classFmdatabasequeue*Queue=[FmdatabasequeueDatabasequeuewithpath:Apath];Use[QueueIndatabase:^(Fmdatabase*Db){ [DbExecuteupdate:@ "INSERT into MyTable VALUES (?)",[NSNumberNumberwithint:1]]; [DbExecuteupdate:@ "INSERT into MyTable VALUES (?)",[NSNumberNumberwithint:2]]; [DbExecuteupdate:@ "INSERT into MyTable VALUES (?)",[NSNumberNumberwithint:3]]; Fmresultset*Rs=[DbExecuteQuery:@ "SELECT * from foo"]; While([RsNext]){ ... }}];If you want to support transactions[QueueIntransaction:^(Fmdatabase*Db,BOOL*Rollback){ [DbExecuteupdate:@ "INSERT into MyTable VALUES (?)",[NSNumberNumberwithint:1]]; [DbExecuteupdate:@ "INSERT into MyTable VALUES (?)",[NSNumberNumberwithint:2]]; [DbExecuteupdate:@ "INSERT into MyTable VALUES (?)",[NSNumberNumberwithint:3 if ( Whoopssomethingwronghappened) { * Rollback = yes; return; } //etc ... [db executeupdate:@ "INSERT Into MyTable VALUES (?) " [nsnumber numberwithint:4< Span class= "P" >]; }];
|
iOS third-party fmdb usage instructions