IOS Data Storage FMDB

Source: Internet
Author: User

Fmdb has three main classes
1. Fmdatabase
A Fmdatabase object represents a separate Sqllite database
Used to execute SQL statements

2.FMResultSet
Result collection after query execution using fmdatabase


3.FMDatabaseQueue
Used to execute multiple queries or updates in multiple threads, which is thread-safe

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

Creating databases and Tables

#import "ViewController.h" @interface Viewcontroller () @property (nonatomic,strong) fmdatabase * db;-(ibaction) InsertData: (ID) sender;-(ibaction) Updata: (ID) sender;-(ibaction) DeleteData: (ID) sender;-(ibaction) Qurey: (ID)        sender; @end @implementation viewcontroller-(void) viewdidload {[Super viewdidload]; Gets the path of the sandbox NSString * Filename=[nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES).        Lastobject stringbyappendingpathcomponent:@ "Student.db"];        1. Create a DB instance Object self.db =[fmdatabase Databasewithpath:filename];        2. Open the database if ([self.db Open]) {NSLog (@ "Database open successfully!"); Create database table BOOL result= [self.db executeupdate:@ "CREATE table if not exists t_student (ID integer PRIMARY key autoincre        ment, name Text,age integer) "]; if (result) {NSLog (@ "CREATE TABLE succeeded!");} else{NSLog (@ "Failed to create TABLE!");}} else{NSLog (@ "Database open failed!");}}

Inserting data

Insert Data-(ibaction) InsertData: (ID) Sender {        BOOL result=[self.db executeupdate:@ "INSERT into t_student (ID, name,age ) VALUES (?,?,?) ", @3,@" Hu Xing ", @38];        if (result) {                NSLog (@ "Insert data successfully!");    } else{                NSLog (@ "Insert number failed!");    }    }

modifying data

Modify Data-(ibaction) Updata: (ID) Sender {        BOOL result =[self.db executeupdate:@ "update t_student Set id =?, age=? where NA Me=? ", @1,@23,@" Feng Yu "];    if (result) {        NSLog (@ "Modify data successfully!");    } else{                NSLog (@ "Failed to modify data!");}    }

Delete data

Delete-(ibaction) DeleteData: (ID) Sender {    //delete the specified name of the person    BOOL result=[self.db executeupdate:@ "Delete from T_ Student where name=? ", @" Zhao three "];        Delete all//    BOOL result =[self.db executeupdate:@ "delete from T_student"];        if (result) {                NSLog (@ "Delete succeeded!");    } else{                NSLog (@ "Delete failed!");    }        }

Querying data

Query data-(ibaction) Qurey: (ID) Sender {        //query specified name information//    fmresultset *rs =[self.db executequery:@ "SELECT * from T_ Student where name like? ", @" Feng Yu "];        Query All information    fmresultset *rs=[self.db executequery:@ "select *from t_student"];    [RS Next] will query from the top down to the bottom of the return value will be no while    ([Rs next]) {                int id =[rs intforcolumn:@ "id"];        int Age=[rs intforcolumn:@ "age"];        NSString * Name =[rs stringforcolumn:@ "name"];              NSLog (@ "%d,%d,%@", id,age,name);            }            Close the database    [self.db close];}

The fmdatabase thread is not secure and we can use Fmdatabasequeue to solve threading problems

@property (nonatomic,strong) fmdatabasequeue * queue; Get the path to the sandbox    NSString * filename=[nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) . Lastobject stringbyappendingpathcomponent:@ "student.db"];        Create a Database Queue instance object    self.queue =[fmdatabasequeue databasequeuewithpath:filename];        [Self.queue indatabase:^ (Fmdatabase *db) {                //CREATE database table        BOOL result=  [db executeupdate:@ "CREATE table if not exists t_student (ID integer PRIMARY key autoi ncrement, name Text,age integer) "];        if (result) {                        NSLog (@ "CREATE TABLE succeeded!");        } else{                        NSLog (@ "CREATE TABLE failed!");        }                    ];

I'm writing a change because of the repetition

[Self.queue indatabase:^ (Fmdatabase *db) {                BOOL result =[db executeupdate:@ "update t_student Set id =?, age=? Where Name=?", @1,@23,@ "Feng Yu"];        if (result) {            NSLog (@ "Modify data successfully!");        } else{                        NSLog (@ "Failed to modify data!");}            ];

If we need to deal with more than one thing and make it complete or not (as long as one thing is not done, it will not be done)

[Self.queue indatabase:^ (Fmdatabase *db) {        //Open transaction  If we need to deal with a few things and make these things complete or not complete (as long as one thing is not done, it will not be completed)        [db  begintransaction];        [DB executeupdate:@ "update t_student Set id =?, age=? Where Name=?", @1,@23,@ "Feng Yu"];        [DB executeupdate:@ "update t_student Set id =?, age=? Where Name=?", @1,@23,@ "Feng Yu"];        if (if found to be incorrect) {            //ROLLBACK TRANSACTION            [db rollback];                         [DB executeupdate:@ "update t_student Set id =?, age=? Where Name=?", @1,@23,@ "Feng Yu"];                    }                Commit TRANSACTION        [DB commit];        [DB executeupdate:@ "update t_student Set id =?, age=? Where Name=?", @1,@23,@ "Feng Yu"];}];     

IOS Data Storage 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.