A brief introduction to SQLite database Framework--fmdb

Source: Internet
Author: User
Tags sqlite sqlite database

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.

A brief introduction to SQLite database Framework--fmdb

Related Article

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.