Fmdb third-party SQLite database in iOS ui_20

Source: Internet
Author: User
Tags sqlite database uikit

1. What is Fmdb?

Fmdb is a SQLite database under the iOS platform, except that it is an OC-style SQLite statement that encapsulates the C language and is used more object-oriented

Advantages of 2.FMDB: 1. Use more object-oriented; 2. Compared with Apple's own Core data management tool is more lightweight, more flexible, and fmdb support cross-platform; 3. Provide multi-thread data security protection mechanism, effectively prevent data confusion


Important classes in 3.FMDM:

Fmdbdatabase: It represents a Database object (this class is used when we need to create a database object)

Fmdbdatabasequeue: It provides multi-threaded execution for find removal, or updated data security

Fmresultset: The set used to store the result of the SQL statement execution (results obtained after we execute the SQL statement are in the object 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 the person objects queried @end@implementation viewcontroller-(void) dealloc{    self.db = nil;    Self.dataarray = nil;    [Super Dealloc];} -(Nsmutablearray *) dataarray{    if (_dataarray = = nil) {        Self.dataarray = [Nsmutablearray arraywithcapacity:0];< c6/>}        return [[_dataarray retain]autorelease];}


Call: (Introduction Fmdb)

-(void) viewdidload {[Super viewdidload]; Get Documents folder path NSString *urlstring = [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask    , YES) Lastobject];    Create a database file in the Documents folder db.sqlite nsstring *dbpath = [urlstring stringbyappendingpathcomponent:@ "Db.sqlite"];    Create database object//parameter: The path//of the database does not help us to generate the database file, just help us to create a database object fmdatabase *db = [Fmdatabase Databasewithpath:dbpath];    NSLog (@ "%@", Nshomedirectory ());    To open the database//open operation to help us really create the database file, and if it has been opened, directly return yes, it can be used directly, if open failure will print error message BOOL IsOpen = [db open];        if (IsOpen) {NSLog (@ "open successfully"); CREATE TABLE//executeupdate In addition to queries, other data create tables, insert data, delete data using this method//blob binary stream equivalent to OC nsdata BOOL iscreat = [db ex ecuteupdate:@ "CREATE table if not exists person (ID integer primary key autoincrement,name Text,gender text,age Integer,pho        to BLOB) "];            NSLog (@ "%@", iscreat @ "Build table Success": @ "Build table failed");    }else{NSLog (@ "Open failed");    }//Assign a value to 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"];       Convert picture to NSData object    nsdata *data = uiimagepngrepresentation (P.photo);        The @ (p.age) parameter must be an object type to use    //insert operation BOOL Isinsert =   [self.db executeupdate:@ "INSERT into person (name,gender,age, Photo) VALUES (?,?,?,?) ", p.name,p.gender,@ (P.age), data];    NSLog (@ "%@", Isinsert @ "Insert succeeded": @ "Insert Failed");}

Delete:

-(Ibaction) Delete: (UIButton *) Sender {    //delete bool result =    [self.db executeupdate:@ "Delete from the person where id =? ", @3];    NSLog (@ "%@", result? @ "Delete succeeded": @ "Delete failed");    Delete all table contents//    BOOL ISRESULT1 = [self.db executeupdate:@ "Delete from person"];    Delete 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 succeeded": @ "update failed");}

Inquire:

-(Ibaction) Select: (UIButton *) Sender {//query all Fmresultset *set = [self.db executequery:@ "SELECT * from"];        Query by condition//Fmresultset *set = [self.db executequery:@ "select *from person where name =?", @ "Guo Meimei"];    Self.dataarray = [Nsmutablearray arraywithcapacity:0]; Loop out the data in the table//[set next] Determines whether a row has data while ([set next]) {//takes out each field corresponding to the data nsinteger ID = [Set Intforcolu  mn:@ "id"];//take out the data under the ID field nsstring *name = [set stringforcolumn:@ "name"];//take out the data under the Name field nsstring *gender = [Set stringforcolumn:@ "Gender"];//remove data under the gender field nsinteger age = [Set intforcolumn:@ ' age '];//remove data under the Age field NSData  *data = [Set dataforcolumn:@ "Photo"];//take out the data under the Photo field//Create model class//convert binary into picture 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 to the next page to see the effect:

you need to prepare a custom cell, Uiviewcontroller Interface and Model Classes

Value using:

-(void) Prepareforsegue: (Uistoryboardsegue *) Segue Sender: (ID) sender{    //Get Segue Start View Controller object    Viewcontroller *ROOTVC  = [Segue Sourceviewcontroller];        This method is triggered when the jump is completed by segue, is triggered before the jump, is generally used to pass    the value//Get push past the View Controller object    Detailviewcontroller *DETAILVC = [Segue Destinationviewcontroller];    Attribute value    Detailvc.datasource = Rootvc.dataarray;}


prepare a Uiviewcontroller:

Detailviewcontroller.h@interface Detailviewcontroller:uitableviewcontroller@property (Nonatomic,retain) Nsmutablearray *datasource;//Property Pass-through value using @enddetailviewcontroller.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 sections. return 1;}  -(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section {//Return the number of rows    The section. return self.dataSource.count;} -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath {Personcell *c    ell = [TableView Dequeuereusablecellwithidentifier:kpersoncell Forindexpath:indexpath]; Build MoDEl class Person *person = Self.datasource[indexpath.row];        Method of calling cell assignment [cell Assginvalues:person]; return cell;}

Prepare a custom cell: implemented by storyboard;

The layout is as follows:



Personcell.h#import <UIKit/UIKit.h> @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 an assignment Method-(void) Assginvalues: (person *) person; @end//========================= ========================personcell.m#import "PersonCell.h" #import "Person.h" @implementation personcell-(void) awakefromnib {//initialization code}//Write an 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 <Foundation/Foundation.h> @class UIImage; @interface Person:nsobject@property (Nonatomic,copy) NSString *name,*gender; @property (nonatomic) Nsinteger age,id;//The basic data type can omit the memory modifier assign, because the default is to use Assign@property ( Nonatomic,retain) UIImage *photo;//Custom Initialization Method-(ID) Initwithname: (NSString *) name Gender: (NSString *) Gender Age: (Nsinte GER) Age Photo: (UIImage *) photo; @end//=============================person.m#import "Person.h" #import <uikit/    uikit.h> @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.phot O];}@end 

The approximate effect does not show all (for reference only):

==============================

Third party Fmdb Download: Http://pan.baidu.com/s/1ntMo3ZN

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Fmdb third-party SQLite database in iOS ui_20

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.