"iOS Development-105" SQLite third-party framework Fmdb, and using Fmdatabasequeue to ensure thread safety

Source: Internet
Author: User

(1): Https://github.com/ccgus/fmdb


(2) Attention points

--The statement can have a semicolon ";", or you can omit the semicolon.

--also need to add "libsqlite3.dylib" library to use.

--in the development of mobile, the database is not closed, that is, not how to use [self.db close], because each time the performance is re-opened, and each time the program shuts down, the database will naturally shut down at the same time.


(3) Usage

#import "ViewController.h" #import "FMDB.h" @interface Viewcontroller () @property (Nonatomic,strong) fmdatabase *db;-( ibaction) Insert: (ID) sender;-(ibaction) Delete: (ID) sender;-(ibaction) Update: (ID) sender;-(ibaction) Select: (ID)    sender; @end @implementation viewcontroller-(void) viewdidload {[Super viewdidload]; NSString *filepath=[[nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) LastObject]    stringbyappendingpathcomponent:@ "Fmdb.sqlite"];    Create database Self.db=[fmdatabase Databasewithpath:filepath];        Open database if ([self.db Open]) {NSLog (@ "Open database succeeded");  To create a table, all operations except select are updated with BOOL createtableresult=[self.db executeupdate:@ "CREATE table IF not EXISTS t_student (ID        Integer PRIMARY KEY autoincrement,name text,age integer) "];        if (Createtableresult) {NSLog (@ "CREATE table succeeded");        }else{NSLog (@ "CREATE TABLE failed");    }}else{NSLog (@ "Failed to open database"); }}-(ibaction) Insert: (ID) sender {for (int index=0; Index<50;        index++) {nsstring *s_name=[nsstring stringwithformat:@ "andy%d", Arc4random ()%100];        NSNumber *[email protected] (arc4random ()%100);    [Self.db executeupdate:@ "INSERT into T_student (name,age) VALUES (?,?)", S_name,s_age]; }}-(ibaction) Delete: (ID) Sender {[self.db executeupdate:@ "Delete from t_student WHERE id=?", @1];} -(ibaction) Update: (ID) Sender {[self.db executeupdate:@ "Update t_student SET name= ' Jack ' WHERE id=?", @2];} -(Ibaction) Select: (ID) Sender {//Get result set, return parameter is query result fmresultset *rs=[self.db executequery:@ "select * from T_student W    Here Age>? ", @50];        while ([Rs next]) {int id=[rs intforcolumn:@ "ID"];        NSString *name=[rs stringforcolumn:@ "NAME"];        int Age=[rs intforcolumn:@ "age"];    NSLog (@ "%d%@%d", id,name,age); }} @end

(4) Use Fmdatabasequeue to ensure thread safety (it is recommended to do so later)

--The main thing is that when you create a database, the database is opened by default

--many subsequent operations, because of the need to operate in the database, it is necessary to use the queue's Indatabase method to bring up the database, execute the operation code in the block.

#import "ViewController.h" #import "FMDB.h" @interface Viewcontroller () @property (nonatomic,strong) Fmdatabasequeue * queue;-(ibaction) Insert: (ID) sender;-(ibaction) Delete: (ID) sender;-(ibaction) Update: (ID) sender;-(ibaction) Select    :(ID) sender; @end @implementation viewcontroller-(void) viewdidload {[Super viewdidload]; NSString *filepath=[[nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) LastObject]    stringbyappendingpathcomponent:@ "Fmdb.sqlite"];    Create the database and join the queue, at this time the database has been opened by default, do not have to open manually, only need to remove the database from the queue self.queue=[fmdatabasequeue Databasequeuewithpath:filepath]; Take out the database, here DB is database, create table in database [Self.queue indatabase:^ (Fmdatabase *db) {//CREATE TABLE BOOL createtableresult=[db E        xecuteupdate:@ "CREATE TABLE IF not EXISTS t_student (ID integer PRIMARY KEY autoincrement,name text,age integer)"];        if (Createtableresult) {NSLog (@ "CREATE table succeeded");        }else{NSLog (@ "CREATE TABLE failed"); }    }];} -(ibaction) Insert: (ID) sender {[SELf.queue indatabase:^ (Fmdatabase *db) {for (int index=0; index<50; index++) {nsstring *s_name=[nsst            Ring stringwithformat:@ "andy%d", Arc4random ()%100];            NSNumber *[email protected] (arc4random ()%100);        [DB executeupdate:@ INSERT into T_student (name,age) VALUES (?,?) ", S_name,s_age]; }    }];} -(Ibaction) Delete: (ID) Sender {[Self.queue indatabase:^ (Fmdatabase *db) {[db executeupdate:@] Delete from T_stu    Dent where id=? ", @1]; }];} -(ibaction) Update: (ID) Sender {[Self.queue indatabase:^ (Fmdatabase *db) {[DB executeupdate:@] Update t_student    SET name= ' Jack ' WHERE id=? ", @2]; }];}  -(Ibaction) Select: (ID) Sender {[Self.queue indatabase:^ (Fmdatabase *db) {//Get result set, return parameter is query result Fmresultset        *rs=[db executequery:@ "SELECT * from T_student where age>?", @50];            while ([Rs next]) {int id=[rs intforcolumn:@ "ID"];            NSString *name=[rs stringforcolumn:@ "NAME"]; int Age=[rs intforcolumn:@ "Age"];        NSLog (@ "%d%@%d", id,name,age); }    }];}

(5) If you want to ensure that multiple operations succeed or fail at the same time, use a transaction, that is, to put multiple operations in the same transaction.

--fmdb, get the database direct operation transaction, as follows:

-(ibaction) Update: (ID) Sender {    [self.queue indatabase:^ (Fmdatabase *db) {        [db begintransaction];        [DB executeupdate:@ "UPDATE t_student SET name= ' Jack ' WHERE id=?", @2];        [DB executeupdate:@ "UPDATE t_student SET name= ' Tomy ' WHERE id=?", @3];        When the situation is not found, the active rollback is made with the following statement. Otherwise, according to the result of the commit, such as success success, if not successful rollback        [db rollback];        [DB executeupdate:@ "UPDATE t_student SET name= ' Eric ' WHERE id=?", @4];        [DB commit];    }];}

The above because the use of the Fmdb package is good, in fact, the original code is this:

[DB executeupdate:@ "BEGIN TRANSACTION"]; [DB executeupdate:@ "ROLLBACK TRANSACTION"]; [DB executeupdate:@ "COMMIT TRANSACTION"];

In--fmdb, the queue can also be used for transactional operations, open, close, rollback transactions, etc. are already encapsulated in the queue.

-(ibaction) Update: (ID) Sender {    [self.queue indatabase:^ (Fmdatabase *db) {        [Self.queue intransaction:^ ( Fmdatabase *db, BOOL *rollback) {            [db executeupdate:@ "UPDATE t_student SET name= ' Jack ' WHERE id=?", @2];            [DB executeupdate:@ "UPDATE t_student SET name= ' Tomy ' WHERE id=?", @3];            When the situation is not found, the active rollback is made with the following statement.            *rollback=yes;            [DB executeupdate:@ "UPDATE t_student SET name= ' Eric ' WHERE id=?", @4];        }];}


iOS Development-105 SQLite third-party framework Fmdb and using Fmdatabasequeue to ensure thread safety

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.