ios-data Persistence-use of third-party framework Fmdb

Source: Internet
Author: User
Tags sqlite sqlite database

Fmdb Brief Introduction

A simple explanation

1. What is Fmdb

Fmdb is the SQLite database framework for the iOS platform

Fmdb encapsulates the C language API of SQLite in OC mode

Advantages of 2.FMDB

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

More lightweight and flexible compared to Apple's own core data framework

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, open the database

To create a Fmdatabase object by specifying the SQLite database file path

Fmdatabase *db = [Fmdatabase Databasewithpath:path];

if (![ DB Open]) {

NSLog (@ "Database open failed! ");

}

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

Iv. implementation of the update

In Fmdb, all operations except queries are called "updates"

Create, DROP, insert, UPDATE, delete, and more

To perform an update using the Executeupdate: method

-(BOOL) Executeupdate: (nsstring*) SQL, ...

-(BOOL) Executeupdatewithformat: (nsstring*) format, ...

-(BOOL) Executeupdate: (nsstring*) SQL Withargumentsinarray: (Nsarray *) arguments

Example

[DB executeupdate:@ "UPDATE t_student SET age =? WHERE name =?; ", @20, @" Jack "]

V. Execution of inquiries

Query method

-(Fmresultset *) ExecuteQuery: (nsstring*) SQL, ...

-(Fmresultset *) Executequerywithformat: (nsstring*) format, ...

-(Fmresultset *) ExecuteQuery: (NSString *) SQL Withargumentsinarray: (Nsarray *) arguments

Example

Querying data

Fmresultset *rs = [db executequery:@ "select * from T_student"];

Traversing result Sets

while ([Rs next]) {

NSString *name = [rs stringforcolumn:@ "name"];

int age = [rs intforcolumn:@ ' age '];

Double score = [Rs doubleforcolumn:@ "score"];

}

Vi. code Examples

1. Create a new project, import the Libsqlite3 library, and include the primary header file in the project

2. Download the third-party framework Fmdb

  

3. Sample Code

YYVIEWCONTROLLER.M file

 1//2//YYVIEWCONTROLLER.M 3//04-fmdb Basic use 4//5//Created by Apple on 14-7-27. 6//Copyright (c) 2014 wendingding. All rights reserved. 7//8 9 #import "YYViewController.h" #import "FMDB.h" @interface Yyviewcontroller () @property (Nonatomic,strong     ) fmdatabase *db;14 @end15 @implementation YYViewController17-(void) VIEWDIDLOAD19 {[Super viewdidload];21 1. Get the path to the database file NSString *doc=[nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) las tobject];23 nsstring *filename=[doc stringbyappendingpathcomponent:@ "Student.sqlite"];24 25//2. Get Database FM         Database *db=[fmdatabase databasewithpath:filename];27 28//3. Open databases if ([DB Open]) {30//4. Genesis 31 BOOL result=[db executeupdate:@ "CREATE TABLE IF not EXISTS t_student (ID integer PRIMARY KEY autoincrement, Name text Not NULL, the age integer is not null); "]; if (result) {NSLog (@ "creation success");}else35 {36            NSLog (@ "Creation failure"), PNS}38}39 self.db=db;40}42 (void) Touchesbegan: (Nsset *) touches Witheve NT: (uievent *) event44 {[Self delete];46] [self insert];47 [self query];48}49 50//Insert data-(void) Insert52 {5 3 for (int i = 0; i<10; i++) {nsstring *name = [NSString stringwithformat:@ "jack-%d", Arc4random_uniform (100)]; //executeupdate: Indeterminate parameters are used to occupy the position of the [self.db executeupdate:@ "INSERT into the T_student (name, age) VALUES (?, ?); ", Name, @ (Arc4random_uniform ())];57//[self.db executeupdate:@" INSERT into T_student (name, age) VAL UES (?,?); "Withargumentsinarray:@[name, @ (Arc4random_uniform (+))]];58//Executeupdatewithformat: No The determined parameters are occupied by%@,%d, etc.//[self.db executeupdatewithformat:@ "INSERT into T_student (name, age) VALUES (%@,%d);" , Name, Arc4random_uniform (40)];61}62}63 64//delete data-(void) delete66 {//[self.db executeupdate:@ "Delete F ROM t_student; "];(self.db executeupdate:@ "DROP TABLE IF EXISTS t_student;"]; [Self.db executeupdate:@ "CREATE TABLE IF not EXISTS t_student (ID integer PRIMARY KEY autoincrement, Name text not NULL, age integer Not NULL); "]; 70}71 72//query-(void) query74 {75//1. Execute Query statement fmresultset *resultset = [self.db executequery:@ "SELECT * FROM         T_student "];77 78//2. Traverse result ([ResultSet next]) {int id = [ResultSet intforcolumn:@ ' id '];81         NSString *name = [resultSet stringforcolumn:@ ' name '];82 int age = [ResultSet intforcolumn:@ ' age '];83 NSLog (@ "%d%@%d", ID, name, age),}85}86 @end

Print View results:

Tips:

If the ID is set to gradual and is set to autogrow, then after deleting the data in the table, reinsert the new data, the ID number is not starting from 0, but the previous ID is numbered.

Attention:

Do not write the following form, do not add ', directly using%@, it will automatically think that this is a string.

--------------------------------------------------------------------------------------------------------------- -----------------------------------------------

Fmdb Database Queue

One, code example

1. You need to import the Fmdb framework and header files first, since the framework relies on the Libsqlite library, you should also import the library.

2. The code is as follows:

 1//2//YYVIEWCONTROLLER.M 3//05-fmdb Database queue 4//5//Created by Apple on 14-7-28. 6//Copyright (c) 2014 wendingding. All rights reserved. 7//8 9 #import "YYViewController.h" #import "FMDB.h" @interface Yyviewcontroller () @property (Nonatomic,strong ) fmdatabasequeue *queue;14 @end15 @implementation YYViewController17-(void) VIEWDIDLOAD19 {[Super Viewdidloa d];21 22//1. Get the path to the database file NSString *doc=[nssearchpathfordirectoriesindomains (nsdocumentdirectory, NSUserDomain Mask, YES) lastobject];24 nsstring *filename=[doc stringbyappendingpathcomponent:@ "Person.sqlite"];25 26//2. Database Queue Fmdatabasequeue *queue=[fmdatabasequeue databasequeuewithpath:filename];28//fmdatabase *db=[FMDatabase D atabasewithpath:filename];29 30//3. Open Database [Queue indatabase:^ (Fmdatabase *db) {+ BOOL result=[db E xecuteupdate:@ "CREATE TABLE IF not EXISTS t_person (ID integer PRIMARY KEY autoincrement, Name text not NULL, age inteGer not NULL); "];         if (result) {NSLog (@ "creation success"),}else36 {PNS NSLog (@ "Failed to create a table"); 38      }39}];40 self.queue=queue;41}43-(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) Event45 {46  Insert data//[Self.queue indatabase:^ (Fmdatabase *db) {//[db executeupdate:@] insert into T_person (name,  Age) VALUES (?,?); ", @" wendingding ", @22];49//}];50 51//query data [self.queue indatabase:^ (Fmdatabase *db) {53//1. Execute Query statement fmresultset *resultset = [db executequery:@ "select * from T_person"];55 56//2 . Traversal results in the ([ResultSet next]) {$ int id = [ResultSet intforcolumn:@ "id"];59 NSString * name = [ResultSet stringforcolumn:@ ' name '];60 int age = [ResultSet intforcolumn:@ ' age '];61 NSLog (@ "%d%@%d", ID, name, age),}63}];64}66 @end

Insert the data first, then query the result, print as follows:

3. Code description

With a queue object, it automatically has a database object inside it, and the operation of the database is thread-safe. second, the businessTransaction, there is a problem if there is no transaction. Example: bank example Zhang San and John Doe account have 1000 yuan, if Zhang three to transfer to John Doe, need to execute two SQL statements, considering security, both of these fish have to either execute successfully, or all failed to execute. Transactions: Put multiple statements in the same transaction, either all succeed or all fail (and automatically rollback if there is a problem in the middle).  The execution of a transaction is atomic. Transaction code Processing: Add multiple statements to a transaction to execute:
1    //Insert Data 2     [Self.queue indatabase:^ (Fmdatabase *db) {3         [db begintransaction];4         [db executeupdate:@] Insert into T_person (name, age) VALUES (?,?), "@" wendingding ", @22];5         [db executeupdate:@" INSERT into T_person (name , age) VALUES (?,?), "@ wendingding", @23];6         [db executeupdate:@ "INSERT into T_person (name, age) VALUES (?,?);", @ "W Endingding ", @24];7         [db executeupdate:@" INSERT into T_person (name, age) VALUES (?,?); ", @" wendingding ", @25];8         [DB Commit];9     }];

If a problem occurs halfway, it is automatically rolled back, or you can choose to roll back manually.

1     //Insert Data 2     [Self.queue indatabase:^ (Fmdatabase *db) {3         [db BeginTransaction]; 4         [DB executeupdate:@] INSERT into T_person (name, age) VALUES (?,?); ", @" wendingding ", @22]; 5         [db executeupdate:@ "INSERT into T_person (name, age) VALUES (?,?);", @ "wendingding", @23]; 6         [db executeupdate: @ "INSERT into T_person (name, age) VALUES (?,?);", @ "wendingding", @24]; 7         [db rollback]; 8         [db executeupdate:@ "INSERT into T_person (name, age) VALUES (?,?);", @ "wendingding", @25]; 9
   [db commit];10     }];

The code above. The first three INSERT statements are obsolete.

Another way to transact:

1    [Self.queue intransaction:^ (Fmdatabase *db, BOOL *rollback) {2         [db executeupdate:@ "INSERT into T_person (name , age) VALUES (?,?), "@ wendingding", @22];3         [db executeupdate:@ "INSERT into T_person (name, age) VALUES (?,?);", @ "W Endingding ", @23];4         [db executeupdate:@" INSERT into T_person (name, age) VALUES (?,?); ", @" wendingding ", @24];5     }];

Description: Open a transaction, start the transaction, then execute the code snippet in the block, and then commit the transaction.

ios-data Persistence-use of third-party framework 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.