iOS Development Database Chapter-fmdb Brief Introduction
A simple explanation
1. What is Fmdb
Fmdb is the SQLite database framework for the iOS platform
Fmdb encapsulates the C language API of SQLite in OC mode
Advantages of 2.FMDB
Use more object-oriented, save a lot of cumbersome, redundant C language code
More lightweight and flexible compared to Apple's own core data framework
Provides a multi-threaded secure database operation method to effectively prevent data confusion
GitHub address for 3.FMDB
Https://github.com/ccgus/fmdb
Second, the Core class
Fmdb has three main classes
(1) Fmdatabase
A Fmdatabase object represents a single SQLite database
Used to execute SQL statements
(2) Fmresultset
Result set after query execution with Fmdatabase
(3) Fmdatabasequeue
Used to execute multiple queries or updates in multiple threads, which is thread-safe
Third, open the database
To create a Fmdatabase object by specifying the SQLite database file path
Fmdatabase *db = [Fmdatabase Databasewithpath:path];
if (![ DB Open]) {
NSLog (@ "Database open failed! ");
}
There are three types of file paths
(1) Specific file path
Automatically created if it does not exist
(2) empty string @ ""
An empty database is created in the temp directory
The database file is also deleted when the Fmdatabase connection is closed
(3) Nil
An in-memory staging database is created and the database is destroyed when the Fmdatabase connection is closed
Iv. implementation of the update
In Fmdb, all operations except queries are called "updates"
Create, DROP, insert, UPDATE, delete, and more
To perform an update using the Executeupdate: method
-(BOOL) Executeupdate: (nsstring*) SQL, ...
-(BOOL) Executeupdatewithformat: (nsstring*) format, ...
-(BOOL) Executeupdate: (nsstring*) SQL Withargumentsinarray: (Nsarray *) arguments
Example
[DB executeupdate:@ "UPDATE t_student SET age =? WHERE name =?; ", @20, @" Jack "]
V. Execution of inquiries
Query method
-(Fmresultset *) ExecuteQuery: (nsstring*) SQL, ...
-(Fmresultset *) Executequerywithformat: (nsstring*) format, ...
-(Fmresultset *) ExecuteQuery: (NSString *) SQL Withargumentsinarray: (Nsarray *) arguments
Example
Querying data
Fmresultset *rs = [db executequery:@ "select * from T_student"];
Traversing result Sets
while ([Rs next]) {
NSString *name = [rs stringforcolumn:@ "name"];
int age = [rs intforcolumn:@ ' age '];
Double score = [Rs doubleforcolumn:@ "score"];
}
Vi. code Examples
1. Create a new project, import the Libsqlite3 library, and include the primary header file in the project
2. Download the third-party framework Fmdb
3. Sample Code
YYVIEWCONTROLLER.M file
1 //2 //YYVIEWCONTROLLER.M3 //04-fmdb Basic Use4 //5 //Created by Apple on 14-7-27.6 //Copyright (c) 2014 wendingding. All rights reserved.7 //8 9 #import "YYViewController.h"Ten #import "FMDB.h" One A @interfaceYyviewcontroller () -@property (nonatomic,strong) fmdatabase *db; - @end the - @implementationYyviewcontroller - -- (void) Viewdidload + { - [Super Viewdidload]; + //1. Get the path to the database file ANSString *doc=[Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) lastobject]; atNSString *filename=[doc stringbyappendingpathcomponent:@"Student.sqlite"]; - - //2. Access to the database -Fmdatabase *db=[Fmdatabase databasewithpath:filename]; - - //3. Open the Database in if([db Open]) { - //4. Create a watch toBOOL result=[db executeupdate:@"CREATE TABLE IF not EXISTS t_student (ID integer PRIMARY KEY autoincrement, name text NOT NULL, age integer NOT NULL); "]; + if(Result) { -NSLog (@"success in the creation of a table"); the}Else * { $NSLog (@"failed to create a table");Panax Notoginseng } - } theself.db=db; + A } the +-(void) Touchesbegan: (Nsset *) touches withevent: (Uievent *)Event - { $ [self delete]; $ [self insert]; - [self query]; - } the - //Inserting DataWuyi-(void) Insert the { - for(inti =0; i<Ten; i++) { WuNSString *name = [NSString stringWithFormat:@"jack-%d", Arc4random_uniform ( -)]; - //executeupdate: Indeterminate parameters are used to occupy the position About[Self.db executeupdate:@"INSERT into T_student (name, age) VALUES (?,?);", Name, @ (Arc4random_uniform ( +))]; $ //[self.db executeupdate:@ "INSERT into T_student (name, age) VALUES (?,?);" Withargumentsinarray:@[name, @ (ARC4 Random_uniform (+))]; - - //Executeupdatewithformat: Indeterminate parameters are occupied by%@,%d, etc. - //[self.db executeupdatewithformat:@ "INSERT into T_student (name, age) VALUES (%@,%d);", Name, Arc4random_unifo RM (+)]; A } + } the - //Delete Data $-(void) Delete the { the //[self.db executeupdate:@ "DELETE from T_student;"]; the[Self.db executeupdate:@"DROP TABLE IF EXISTS t_student;"]; the[Self.db executeupdate:@"CREATE TABLE IF not EXISTS t_student (ID integer PRIMARY KEY autoincrement, name text NOT NULL, age integer NOT NULL); "]; - } in the //Enquiry the- (void) Query About { the //1. Execute the query statement theFmresultset *resultset = [self.db executeQuery:@"SELECT * from T_student"]; the + //2. Traverse the results - while([ResultSet next]) { the intID = [ResultSet intforcolumn:@"ID"];BayiNSString *name = [ResultSet stringforcolumn:@"name"]; the intAge = [ResultSet intforcolumn:@" Age"]; theNSLog (@"%d%@%d", ID, name, age); - } - } the the @end
Print View results:
Tips:
If the ID is set to gradual and is set to autogrow, then after deleting the data in the table, reinsert the new data, the ID number is not starting from 0, but the previous ID is numbered.
Attention:
Do not write the following form, do not add ', directly using%@, it will automatically think that this is a string.