In iOS, FMDB third-party SQLite database UI_20
1. What is FMDB?
FMDB is an SQLite database on iOS platform, but it encapsulates SQLite statements in C language in the OC mode and is more object-oriented.
2. advantages of FMDB: 1. it is more object-oriented. 2. compared with Apple's Core Data management tools, the tool is more lightweight and flexible, and supports cross-platform FMDB. provides a multi-threaded data security protection mechanism to effectively prevent data confusion.
3. Important FMDM classes:
FMDBDataBase: it represents a database object (this class is used when we need to create a database object)
FMDBDataBaseQueue: it provides multi-threaded query and deletion or updated data security protection.
FMResultSet: The set used to store the SQL statement execution results (the results obtained after the SQL statement is executed are all in the objects of this class)
ViewController. m
# Import FMDB. h # import Person. h # import DetailViewController. h @ interface ViewController () @ property (nonatomic, retain) FMDatabase * db; @ property (nonatomic, retain) NSMutableArray * dataArray; // store all queried Person objects @ end @ implementation ViewController-(void) dealloc {self. db = nil; self. dataArray = nil; [super dealloc];}-(NSMutableArray *) dataArray {if (_ dataArray = nil) {self. dataArray = [NSMutableArray arrayWithCapacity: 0];} return [[_ dataArray retain] autorelease];}
Call: (introducing FMDB)
-(Void) viewDidLoad {[super viewDidLoad]; // obtain the folder path NSString * urlString = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; // create the database file db in the Documents folder. sqlite NSString * dbPath = [urlString stringByAppendingPathComponent: @ db. sqlite]; // create a database object // parameter: Database path // The database file is not generated for us after execution, just helped us create the database object FMDatabase * db = [FMDatabase databaseWithPath: dbPath]; NSLo G (@ % @, NSHomeDirectory (); // on behalf of the database // open operation to help us create a database file, and if it has been opened, return YES directly, in this case, you can use it directly. if it fails to be opened, the error message BOOL isOpen = [db open] will be printed; if (isOpen) {NSLog (@ opened successfully ); // create a table // executeUpdate: In addition to queries, other data can be used to create a table, this method is used to insert and delete data. // blob binary stream is equivalent to the NSData BOOL isCreat of oc = [db executeUpdate: @ create table if not exists Person (id integer primary key autoincrement, name text, gender text, age integer, photo blob)]; NSLog (@%@, isCreat? @ Table created successfully: @ table created failed);} else {NSLog (@ failed to open);} // assign the attribute self. db = db; NSLog (@%@, NSHomeDirectory ());}
Insert:
-(IBAction) insert :( UIButton *) sender {Person * p = [[Person alloc] initWithName: @ Guo Meimei gender: @ female age: 20 photo: [UIImage imageNamed: @ 3.gif]; // converts an image to an NSData object NSData * data = UIImagePNGRepresentation (p. photo); // @ (p. age) the BOOL isInsert = [self. db executeUpdate: @ insert into Person (name, gender, age, photo) values (?,?,?,?), P. name, p. gender, @ (p. age), data]; NSLog (% @, isInsert? @ Successful insertion: @ insertion failed );}
Delete:
-(IBAction) delete :( UIButton *) sender {// delete BOOL result = [self. db executeUpdate: @ delete from Person where id = ?, @ 3]; NSLog (% @, result? @ Successful deletion: @ failed to delete); // delete all table content // BOOL isResult1 = [self. db executeUpdate: @ delete from Person]; // delete a table // BOOL isResult2 = [self. db executeUpdate: @ drop table Person];}
Update:
-(IBAction) update :( UIButton *) sender {BOOL isUpdate = [self. db executeUpdate: @ update Person set gender =? Where id = ?, @ Male, @ 4]; NSLog (@ % @, isUpdate? @ Update successful: @ update failed );}
Query:
-(IBAction) select :( UIButton *) sender {// query all FMResultSet * set = [self. db executeQuery: @ select * from Person]; // query by condition // FMResultSet * set = [self. db executeQuery: @ select * from Person where name = ?, @ Guo Meimei]; self. dataArray = [NSMutableArray arrayWithCapacity: 0]; // cyclically retrieves data from the table. // [set next] checks whether a row has data while ([set next]) {// retrieve the data NSInteger ID = [set intForColumn: @ id] for each field; // retrieve the data NSString * name = [set stringForColumn: @ name] under the id field; // retrieve the data NSString * gender = [set stringForColumn: @ gender] under the name field; // retrieve the data NSInteger age = [set intForColumn: @ age] under the gender field; // retrieve the data NSData * data = [set dataForColumn: @ photo] under the age field; // retrieve the data in the photo field // create a model class // convert the binary data into an image. UIImage * image = [UIImage imageWithData: data]; person * p = [[Person alloc] initWithName: name gender: gender age: age photo: image]; p. ID = ID; [self. dataArray addObject: p]; [p release] ;}}
To show the effect, we push it to the next page to view the effect:
You need to prepare a custom cell, UIViewController interface, and model class.
Use:
-(Void) prepareForSegue :( UIStoryboardSegue *) segue sender :( id) sender {// gets the ViewController object of the Start side of the segue * rootVC = [segue sourceViewController]; // This method is triggered when the jump is completed through the segue, which is triggered before the jump, it is generally used to pass the value // obtain the View Controller object DetailViewController * detailVC = [segue destinationViewController] After the push is passed; // The attribute transmits the value detailVC. dataSource = rootVC. dataArray ;}
Prepare a UIViewController:
DetailViewController. h @ interface DetailViewController: UITableViewController @ property (nonatomic, retain) NSMutableArray * dataSource; // use @ endDetailViewController to pass the attribute value. m # import DetailViewController. h # import Person. h # import PersonCell. h # define kPersonCell @ personcell @ interface DetailViewController () @ end @ implementation DetailViewController-(void) dealloc {self. dataSource = nil; [super dealloc];}-(void) viewDidLoad {[super viewDidLoad];} # pragma mark-Table view data source-(NSInteger) numberOfSectionsInTableView :( UITableView *) tableView {// Return the number of sessions. return 1;}-(NSInteger) tableView :( UITableView *) tableView numberOfRowsInSection :( NSInteger) section {// Return the number of rows in the section. return self. dataSource. count;}-(UITableViewCell *) tableView :( UITableView *) tableView cellForRowAtIndexPath :( NSIndexPath *) indexPath {PersonCell * cell = [tableView progress: kPersonCell forIndexPath: indexPath]; // create model class Person * person = self. dataSource [indexPath. row]; // call the cell assignment method [cell assginValues: person]; return cell ;}
Prepare a custom cell: implemented through storyBoard;
The layout is as follows:
PersonCell. h # import
@ Class Person; @ interface PersonCell: UITableViewCell @ property (retain, nonatomic) IBOutlet UILabel * nameLabel; @ property (retain, nonatomic) IBOutlet UILabel * genderLabel; @ property (retain, nonatomic) IBOutlet UILabel * ageLabel; @ property (retain, nonatomic) IBOutlet UIImageView * photoView; @ property (retain, nonatomic) IBOutlet UILabel * IDLabel; // write a value assignment method-(void) assginValues: (Person *) person; @ end // ============================================ =============== PersonCell. m # import PersonCell. h # import Person. h @ implementation PersonCell-(void) awakeFromNib {// Initialization code} // write a value assignment method-(void) assginValues: (Person *) person {self. nameLabel. text = person. name; self. genderLabel. text = person. gender; self. ageLabel. text = [NSString stringWithFormat: @ % ld, person. age]; self. photoView. image = person. photo; self. IDLabel. text = [NSString stringWithFormat: @ % ld, person. ID];}-(void) dealloc {[_ nameLabel release]; [_ genderLabel release]; [_ ageLabel release]; [_ photoView release]; [_ IDLabel release]; [super dealloc];} @ end
Prepare a model class:
Person. h # import
@ Class UIImage; @ interface Person: NSObject @ property (nonatomic, copy) NSString * name, * gender; @ property (nonatomic) NSInteger age, ID; // The Memory modifier assign can be omitted for the basic data type, because the default value is assign @ property (nonatomic, retain) UIImage * photo; // custom initialization method-(id) initWithName: (NSString *) name gender: (NSString *) gender age: (NSInteger) age photo: (UIImage *) photo; @ end // ================================ Person. m # import Person. h # import
@ Implementation Person-(void) dealloc {self. name = nil; self. gender = nil; self. photo = nil; [super dealloc];} // custom initialization method-(id) initWithName: (NSString *) name gender: (NSString *) gender age: (NSInteger) age photo: (UIImage *) photo {if (self = [super init]) {self. name = name; self. gender = gender; self. age = age; self. photo = photo;} return self;}-(NSString *) description {return [NSString stringWithFormat: %@% ld % @, self. name, self. gender, self. age, self. photo];} @ end
The approximate effect cannot be all (for reference only ):