The use of iOS development--fmdb

Source: Internet
Author: User

In many cases, we will use the database, our mobile use of the database, is generally embedded database, is a relatively light-weight database,

In general, many times, the third party of Fmdb, which is packaged by Daniel, is enough to meet our needs!

Now share your own learning experience, hope to help everyone!

I. Brief description

1. What is Fmdb

Fmdb is the SQLite database framework for the iOS platform

Fmdb is an OC-encapsulated C-language API for SQLite

Advantages of 2.FMDB

Use more object-oriented, save a lot of cumbersome, redundant C language code

Compare the CoreData frame with Apple's own, more lightweight and flexible

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, Fmdb use steps

Download the Fmdb file and add the Fmdb folder to your project (you can also use Cocoapods import)

Importlibsqlite3.0框架,导入头文件FMDatabase.h

Code implementation, similar to SQLite using steps, create a database path, get the database path, open the database, and then

Database to increase, delete, change, check operation, and finally close the database.

Create Fmdatabase object is the parameter for SQLite database file path, this path can be one of three ways

File path, the file path does not need to be real, if it does not exist it will be created automatically

An empty string (@ ""). Indicates that an empty database is created in the Temp directory and the file is deleted when the Fmdatabase connection is closed

Null. An intrinsic database will be created, and the data will be destroyed when the Fmdatabase connection is closed.

I use the data model myself:

@property (nonatomic,assign)int ID; // ID@property (nonatomic,strong) NSString *name; // name@property (nonatomic,strong) NSString *age; //  Age

I use the tool class myself:

. h

#import <Foundation/Foundation.h>@interface Databasetools:nsobject//Create a singleton class+(instancetype) Sharedmanager;//Initializing the database-(void) initdatabase;//Inserting Data-(void) Insert;//Delete Data-(void) Deleteswithbyids: (NSString *) Ida;//Querying Data-(Nsmutablearray *) Querywithbyids: (int) Ida;//operations that are completely destroyed-(void) Allremovesdatas; @end

. m

#import"DataBaseTools.h"#import"FMDB.h"#import"FMDatabase.h"#import"FMModel.h"Fmdatabase*__db =Nil; @implementation Databasetools//Create a singleton class+(instancetype) sharedmanager{StaticDatabasetools *database =Nil; Staticdispatch_once_t Once_token; Dispatch_once (&once_token, ^{dataBase=[[Self alloc]init];    }); returndataBase;}//Initializing the database-(void) initdatabase{//getting the database file path is not necessarily true, it can be empty, and if it is empty, createNSString *doc =[Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) lastobject]; NSString*filename = [Doc stringbyappendingpathcomponent:@"Student.sqlite"]; //Get the databaseFmdatabase *db =[Fmdatabase Databasewithpath:filename]; //Open Database    if([db Open]) {//If you open it, you don't create it.BOOL 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 (@"created successfully"); }Else{NSLog (@"creation failed"); } __db=DB; }}//Inserting Data-(void) insert{ for(inti =0; i<Ten; i++) {NSString*names = [NSString stringWithFormat:@"h_jack%d", Arc4random_uniform ( -)]; //Unsure of the parameters to use? To occupy a position[__db executeupdate:@"INSERT into T_student (name, age) VALUES (?,?);", names,@ (Arc4random_uniform ( -))]; }}//Delete Data-(void) Deleteswithbyids: (NSString *) ida{//to delete a fixed value//nsstring *namestr = @ "h_jack35";[__db executeupdate:@"Delete from t_student where name =?;", Ida]; //[__db executeupdate:@ "Delete from t_student where age =?;", Ida];    }//Querying Data-(Nsmutablearray *) Querywithbyids: (int) ida{//Execute Query Statement--Query the entire tableFmresultset *resultset = [__db executeQuery:@"SELECT * from T_student"]; //Query by ConditionFmresultset *resultsets = [__db executeQuery:@"SELECT * from t_student where ID >?", [NSString stringWithFormat:@"%d", Ida]]; Nsmutablearray*array = [Nsmutablearray arraywithcapacity:0]; //Traverse Results     while([resultsets next]) {Fmmodel*model = [FmmodelNew]; Model.id= [ResultSets intforcolumn:@"ID"]; Model.name= [ResultSets stringforcolumn:@"name"]; Model.age= [ResultSets stringforcolumn:@" Age"];    [Array Addobject:model];        } [ResultSets close]; returnArray;}//operations that are completely destroyed-(void) allremovesdatas{//If the table exists, destroy the[__db executeupdate:@"drop table if exists t_student"];}

The above operation has been increased, deleted, changed and checked,

Four, in the TableView to show the inserted data, and then I did a left slide delete operation, the specific code is as follows:

//Add-(void) insertclick{[[Databasetools Sharedmanager] insert];}//Find-(void) insertsclick{Self.onearray=[[Databasetools Sharedmanager] Querywithbyids:[tf1.text Intvalue]];    [Self.tableview Reloaddata]; NSLog (@"--array is%@", Self.onearray);}-(void) creattableview{Self.tableview= [[UITableView alloc]initwithframe:cgrectmake (0, -, Self.view.frame.size.width, Self.view.frame.size.height) Style:uitableviewstyleplain]; Self.tableview.Delegate=Self ; Self.tableView.dataSource=Self ; Self.tableView.tableFooterView=[[UIView alloc]init]; [Self.tableview registernib:[uinib Nibwithnibname:@"Fmcell"Bundle:nil] Forcellreuseidentifier:@"Fmcell"]; [Self.view AddSubview:self.tableView];}-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) section{returnSelf.oneArray.count;}-(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) indexpath{return  -;}-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexpath{Fmcell*cell = [TableView dequeuereusablecellwithidentifier:@"Fmcell"Forindexpath:indexpath];; Fmmodel*model =Self.onearray[indexpath.row]; Cell. Idlab.text= [NSString stringWithFormat:@"%d", Model.id]; Cell.nameLab.text=Model.name; Cell.ageLab.text=Model.age; returncell;}-(NSString *) TableView: (UITableView *) TableView Titlefordeleteconfirmationbuttonforrowatindexpath: (Nsindexpath *) indexpath{return @"Delete";}-(Uitableviewcelleditingstyle) TableView: (UITableView *) TableView Editingstyleforrowatindexpath: (Nsindexpath *) indexpath{returnUitableviewcelleditingstyledelete;}-(Nullable nsarray<uitableviewrowaction *> *) TableView: (UITableView *) TableView Editactionsforrowatindexpath :(Nsindexpath *) Indexpath Ns_available_ios (8_0) __tvos_prohibited{uitableviewrowaction* Deleteaction = [uitableviewrowaction rowactionwithstyle:uitableviewrowactionstylenormal title:@"Delete"handler:^ (uitableviewrowaction * _nonnull action, Nsindexpath *_nonnull Indexpath) {        //This inside writes the click button of the event that responds to theFmmodel *model =Self.onearray[indexpath.row]; NSLog (@"----%@--%ld", Model.name,indexpath.row);        [[Databasetools Sharedmanager] deletesWithByids:model.name];        [Self.onearray RemoveObjectAtIndex:indexPath.row];        [Self.tableview Deleterowsatindexpaths:@[indexpath] withrowanimation:uitableviewrowanimationfade];            [Self.tableview Reloaddata];        }]; Deleteaction.backgroundcolor=[Uicolor Redcolor]; return@[deleteaction]; }

The end result is as follows:

After the left slide delete, the data is deleted directly from the database!

The use of iOS development--fmdb

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.