The simple use of FMDB developed by iOS

Preface

Before the use of SQLite is very troublesome, the code is redundant, so developers friends generally in the actual development process is the use of this framework is FMDB Kaiyuan, so we will try to understand the simple use of this lightweight FMDB framework.

  • Basic concept: the so-called FMDB is the iOS platform’s SQLite database framework. It encapsulates SQLite’s C language API. in OC
  • The advantages of using FMDB: 2.1, FMDB is more object-oriented than SQLite, save a lot of trouble in the operation, reduce the redundancy of the C language code.
    2.2, provides a database operation method of multi thread safe, effective to prevent the object to access the database at the same time caused by data disorder phenomenon.
  • Use the FMDB’s note: manually loading FMDB: requires dragging source from the fmdb into the project and adding the libsqlite3.0.tbd static library that requires header files to be inserted into the PCH file
  • The basic structure of FMDB focuses on the three core classes of FMDB,
    3.1, and FMDatabase:, and a FMDatabase object represents a SQLite database. Used to execute SQL statements.
    3.2, FMResultSet: uses FMDatabase to execute the query. The result set
    3.3, FMDatabaseQueue:, is used to perform updates and queries in multiple threads. It is ready and safe
  • How to open the database and note: open the database is to create a FMDatabase object through the SQLite database file path specified. / / *db = [FMDatabase open database FMDatabase databaseWithPath:filePath]; if ([db! Open]) {NSLog (@ “open database failure, direct return”); return;} note: file path the following three conditions:
    5.1, file path specific: it means if the path does not exist, the system will automatically create a path.
    5.2, the empty string “@”: create an empty database in the temporary directory, only when the FMDatabase connection is closed, the database files will be deleted.
    : 5.3, nil will create a temporary database in memory, when the FMDatabase connection is closed, The database file will also be deleted
  • Update update: 6, in FMDB, in addition to the query, all operations are update operation, use the executeUpdate: method to update [db executeUpdate:@ UPDATE t_student SET age = WHERE; name =?? “, @ @20,” Alex “];
  • Executive query]
Use the executeQuery: method to execute the query: query data FMResultSet = [db *rs / executeQuery:@ SELECT * FROM t_student "]; / / while ([rs traversal result set next]) {NSString *name = [rs stringForColumn:@" name "]; int age = [rs intForColumn:@" age "]; double score = [rs doubleForColumn:@" score "];}
  • FMDatabaseQueue (queue: default is thread safe)
FMDatabaseQueue: FMDatabase is a class that is not thread safe, if multiple threads access the database at the same time, the data will cause the disorder phenomenon. Therefore, in order to ensure thread safety issues for us, FMDB provides a safe and convenient FMDatabaseQueue FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:path];
  • close database
Close the database: the close method that calls the database directly is: [db close]

Here is a simple example of using FMDB

  • Prepare for the premise of using FMDB
How does The simple use of FMDB developed by iOS
manually import FMDB.png?
  • Set storyboard
    The simple use of FMDB developed by iOS
    Snip20160804_4.png
/ / / / ViewController.m / / FMDB / / Created / / by Alex simple to use William on 16/8/4. Copyright WeiKa. All rights of 2016 / / reserved. / / / * create database and data table of basic steps: 1, the absolute path splicing save the database 2, through the path to create database 3, open database (open to execute SQLite statements) * / #import "ViewController.h" @interface (ViewController) @property (nonatomic, strong) FMDatabaseQueue *queue; @end @implementation ViewController (void) {viewDidLoad [super viewDidLoad]; / / get the address of the NSString *path sandbox = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES, lastObject]); / / NSString *filePath = [path stringByAp full path Splicing Database PendingPathComponent:@ "student.sqlite"]; / / print database address NSLog (@ filePath, filePath =%@ "); / / create a FMDatabaseQueue object / / as long as the database is created queue object, FMDB will automatically help us to load the database object self.queue = [FMDatabaseQueue databaseQueueWithPath:filePath]; / / operation (internal transfer will create good database for us by block [self.queue inDatabase:^) (FMDatabase *db) {/ / create table (in the FMDB framework, add / delete / modify / creation / destruction operations are update BOOL success) = [db executeUpdate:@ CREATE TABLE IF NOT EXISTS t_student (ID INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL score REAL DEFAULT, 1);"]; if (success) {NSL Og (@ "create table");} else {NSLog (@ "create table failure");}}];} / / insert - (IBAction) insertOnClicked: (ID) sender [self.queue inDatabase:^ (FMDatabase *db) {{/ / / / insert data in FMDB can be used as a placeholder?, but note: if use a question mark as a placeholder, after only to mark BOOL success = [db executeUpdate:@ objects INSERT INTO t_student (ID, name, score) VALUES (?,?,?); and (1) @, @ Alex, @ (99)]; if (success) {NSLog (@ "insert the success of data");} else {NSLog (@ "insert data failure");}}];} / / delete - (IBAction) deletedOnClicked: (ID sender) {} / / modify - (IBAction) upDateOnCliked: (ID) {[sender Self.queue inDeferredTransaction:^ (FMDatabase *db, BOOL *rollback) {BOOL success = [db executeUpdateWithFormat:@ UPDATE t_student SET score = 100 WHERE name ='Alex'; "]; if (success) {NSLog (@" changed ");} else {NSLog (@" modify failure ");}} - (}]; / / query IBAction) queryOnClicked: (ID) sender [self.queue inDatabase:^ (FMDatabase *db) {{/ / in the FMDB framework in addition to check all operations are update operation, and query operations using the executeQuery operation in the use of / / query method, need to use the FDMB FMResultSet FMResultSet result set *results = [db executeQuery:@ SELECT ID, name. Score FROM t_student;"]; / / next method if the return is YES, that is The data available, if the return NO while ([results next]) query failed {/ / there are two ways to get the data in the database: int ID / * a = [results intForColumnIndex:0]; NSString *name = [results stringForColumnIndex:1]; double score = [results doubleForColumnIndex:2]; NSLog (@ "ID =%d, name = score =%f% @." ID, name, score); / / * / two: int = ID [results intForColumn:@ "Id"]; NSString *name = [results stringForColumn:@ "name"]; double score = [results doubleForColumn:@] "score"; NSLog (@ ID =%d, name = score =% @,%f, ID. Name, score);}}}]; @end