IOS development-encapsulation database sqlite3: Why FMDB and sqlite3fmdb

Source: Internet
Author: User

IOS development-encapsulation database sqlite3: Why FMDB and sqlite3fmdb

Why is FMDB a third-party Lightweight Framework used?

FMDB is a third-party framework for Data storage. Compared with SQLite and Core Data, FMDB has many advantages.

FMDB Is Object-Oriented. It encapsulates the C language API of SQLite in OC mode, which is more convenient to use and does not require much knowledge about database operations.

Why not use core data and SQLite?

Core Data is an embodiment of ORM, implementing interface-based operations. Using Core Data requires the conversion of model Data. Although the operation is simple, you do not need to directly operate the database, but the performance is not directly high with SQLite. However, when using SQLite, you need to use functions in the C language, which is difficult to operate. Therefore, you need to encapsulate it. However, if it is simply encapsulated, it is likely to ignore many important details, such as how to handle concurrency and security issues.

The following is a simple encapsulation of sqlite to understand why FMDB is so useful?

Create an SqleiteManage class to implement encapsulation:

1 # import "SqleiteManage. h "2 static SqleiteManage * manage = nil; 3 @ implementation SqleiteManage 4 5 // The Single Instance must be the same database 6 + (instancetype) shareManage {7 static dispatch_once_t onceToken; 8 dispatch_once (& onceToken, ^ {9 manage = [[SqleiteManage alloc] init]; 10 11}); 12 13 return manage; 14} 15 16 // Open Database 17-(int) openDB :( NSString *) str {18 // 1. open Database Table creation 19 NSString * dbpath = [[NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: str]; 20 NSLog (@ "% @", dbpath ); 21 22 // Open Database 23 result = sqlite3_open ([dbpath UTF8String], & db); 24 if (SQLITE_ OK = result) {25 NSLog (@ "opened successfully "); 26} else {27 NSLog (@ "failed to open"); 28} 29 30 return result; 31 32} 33 34 // closes the database 35-(int) closeDB {36 return sqlite3_close (db); 37} 38 // ------ create a table 39-(BOOL) creatTableWithSqlite :( NSString *) SQL {40 41 if (result = SQLITE_ OK) {42 43 // SQL statement 44 // primary key autoincrement defines id as the primary key value to automatically increase 45 // not null unique cannot be blank cannot be repeated 46 // create table formula 47 // create table name (data type of field Name field, data Type of the field Name field ........); 48 // NSString * SQL = @ "create table if not exists user (id integer primary key autoincrement, name text not null unique, phone text, creatDate text );"; 49 char * error; 50 int resul = sqlite3_exec (db, [SQL UTF8String], NULL, NULL, & error); 51 [self closeDB]; 52 if (resul = SQLITE_ OK) {53 54 NSLog (@ "table created successfully"); 55 return YES; 56 // return jump out of the entire function 57 // black is jump out of brackets 58 59} else {60 NSLog (@ "% s", error); 61 return NO; 62} 63 64} 65 return NO; 66} 67 68 // insert 69-(BOOL) insertMessageWithSql :( NSString *) SQL {70 if (result = SQLITE_ OK) {71 char * error; 72 int resul = sqlite3_exec (db, [SQL UTF8String], NULL, NULL, & error); 73 [self closeDB]; 74 if (resul = SQLITE_ OK) {75 return YES; 76} else {77 return NO; 78} 79 80} 81 82 return NO; 83 84} 85 86 // Delete 87-(BOOL) deleteMessageWithSql :( NSString *) SQL {88 if (result = SQLITE_ OK) {89 char * error; 90 int resul = sqlite3_exec (db, [SQL UTF8String], NULL, NULL, & error); 91 [self closeDB]; 92 if (resul = SQLITE_ OK) {93 return YES; 94} else {95 return NO; 96} 97 98} 99 return NO; 100} 101 102 // modify 103-(BOOL) modifyMessageWithSql :( NSString *) SQL {104 if (result = SQLITE_ OK) {105 char * error; 106 int resul = sqlite3_exec (db, [SQL UTF8String], NULL, NULL, & error ); 107 [self closeDB]; 108 if (resul = SQLITE_ OK) {109 return YES; 110} else {111 return NO; 112} 113 114} 115 return NO; 117} 118 119-(NSArray *) queryMessageWithSQL :( NSString *) SQL andObject :( NSString *) obj {120 if (result = SQLITE_ OK) {121 // declare that the query results of a result set are stored in the result set. 122 sqlite3_stmt * stmt; 123 // check whether the SQL statement is correct when int nByte is-1. The query length is not limited to 124 if (sqlite3_prepare_v2 (db, [SQL UTF8String],-1, & stmt, NULL) = SQLITE_ OK) {125 // like fuzzy query 126 127 NSString * searchContent = [NSString stringWithFormat: @ "% @ %", obj]; 128 // bind the content to be queried 129 if (sqlite3_bind_text (stmt, 1, [searchContent UTF8String],-1, NULL) = SQLITE_OK130) {131 NSMutableArray * resultlist = [NSMutableArray array]; 132 // loop query 133 while (sqlite3_step (stmt) = SQLITE_ROW) {134 // integrate the queried data into a dictionary. 135/1 indicates the number of columns of the Data queried by icol. 136 char * name = (char *) sqlite3_column_text (stmt, 1); 138 char * phone = (char *) sqlite3_column_text (stmt, 2); 139 char * time = (char *) sqlite3_column_text (stmt, 3 ); 140 NSDictionary * info ={ @ "name": [NSString stringwithuf8string: name], @ "phone": [NSString stringwithuf8string: phone], @ "time": [NSString stringwithuf8string: time] ,}; 141 [resultlist addObject: info]; 142} 143 [self closeDB]; 144 return resultlist; 145 146 147} 148 149} 150 return nil; 151} 152 @ end

Encapsulated and used:

# Import "ViewController. h "# import" SqleiteManage. h "@ interface ViewController () // Database: organizes, stores, and manages data according to the data structure. // The Database is basically composed of tables and relationships, operation composition // commonly used in mobile platform development is SQLite // every column in the table is a field (clumn, attribute) // you can find the corresponding data through the field. // ios uses the C language to operate the database. // you can add the corresponding data before using the database; ibsqlite3 framework # import <> @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; // ************* database related concepts ****************/important methods for ios to use the database open the database: sqloud E3_open () Create Table modification add update delete data: sqlite3_exec () query: 1. verify whether the statement is valid: sqlite3_prepare_v2 2. bind the data to be queried and SQL statement: sqlite3_bind_text 3. loop search content (by row): sqlite3_step 4. take out the data in this row (based on the corresponding type): sqlite3_column_text close the database: sqlite3_close () SQL (Strured Query Language) is a structure Query Language SQL features: each sentence is followed by a keyword; the keyword "create update delete from where by table" does not end with a case-insensitive SQL statement... Keywords cannot be used in the database to name the table name or strings in the field database. To enclose sqlite with single quotation marks, Formula 1 is used for Relational Database SQL statements. create table @ "create table (field Name field type, field name, field type);" 2. create table if not exists table name (field name, field type,) for example: @ "create table if not exists user (id integer, name text, phone text) insert: insert into Table Name (field, field) vlaus ('content', 'content') delete: delete from table name where field = 'content to be deleted' modify data: update table name set field = 'Modified content 'where field = 'pre-modified content'; query: (1) select * from table name query all fields (* indicates all );( 2) sele Field 1, Field 2 ,...... from table name; database usage formula: Import framework 1. create a database and open the database. 2. create Table 3. add, delete, modify, query, and close the database //******************************* * **************************/SqleiteManage * manage = [SqleiteManage shareManage]; // open the database [manage openDB: @ "shujuku .. sqlite "]; BOOL seccess = [manage creatTableWithSqlite: @" create table if not exists user (id integer primary key autoincrement, name text not null unique, phone Text, creatDate text); "]; if (seccess) {NSLog (@" table created successfully ");} // insert data formula // insert into Table Name (field, field) values ('','', ''); NSString * name = @" Xiao ah "; NSString * tel = @" 13298822122 "; NSString * date = @ "2088-12-25"; // insert data NSString * SQL = [NSString stringWithFormat: @ "insert into user (name, phone, creatDate) values ('% @', '% @', '% @'); ", name, tel, date]; if ([manage insertMessageWithSql: SQL] = YES) {NSLog (@" insert Data succeeded ");} // delete data if ([manage deleteMessageWithSql: @" delete from user where name = 'xiaoming '; "] = YES) {NSLog (@ "data deleted");} if ([manage modifyMessageWithSql: @ "update user set name = 'rhubarb man 'where name = 'Prince charming '; "] = YES) {NSLog (@" data modified ");} // query data NSArray * list = [manage queryMessageWithSQL: @" select id, name, phone, creatDate from user where name like ?; "AndObject: @" "]; if (list. count! = 0) {NSLog (@ "% @", list) ;}}-(void) didReceiveMemoryWarning {[super didreceivemorywarning]; // Dispose of any resources that can be recreated .} @ end

After encapsulation, sqlite reduces a lot of code, and FMDB can be used very well. It also handles the problem of multi-thread concurrency. The same is true for FMDB encapsulation.

 

Related Article

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.