iOS development: Fmdb Data Storage Resolution

Source: Internet
Author: User
Tags bool sqlite sqlite database

Fmdb is object-oriented, it encapsulates the SQLite C language API in OC, it is more convenient to use, do not need too much care about database operation knowledge. But it also has some problems, such as cross-platform, because it is packaged in the language of OC, so it can only be used in the development of iOS, if you want to achieve cross-platform operations to reduce the cost of development and maintenance costs, you need to use the more primitive sqlite.

Fmdb is a third-party framework for data storage, and it has many advantages over sqlite and core data.

Core data is an ORM embodiment of the use of core data need to use the transformation of the model, although the operation is simple, do not need to directly manipulate the database, but the performance is not directly used SQLite high. However, the use of SQLite needs to use the C language function, the operation is more cumbersome, so it needs to be encapsulated. But if you simply encapsulate it, you're likely to overlook a lot of important details, such as how to handle concurrency and security issues.

Therefore, it is recommended here to use a Third-party framework Fmdb, which is the encapsulation of the LIBSQLITE3 framework, the steps used are similar to the SQLite use, and it for multithreading at the same time to manipulate a table processing, it means that it is thread-safe. Fmdb is a lightweight framework that is flexible to use and is the first choice for many enterprise development.

Important classes in the Fmdb

Fmdatabase: A Fmdatabase object represents a separate SQLite database for executing SQL statements

Fmresultset: Result set after query is executed using Fmdatabase

Fmdatabasequeue: Used to execute multiple queries or updates in multiple threads, it is thread-safe

Fmdb Use steps

1. Download Fmdb file Fmdb download address, add Fmdb folder to Project

2. Import SQLite frame, import FMDatabase.h file

3. Similar to the SQLite use step, you need to get the database file path, then get the database, open the database, then operate the database, and finally close the database. The code looks like this:

Viewcontroller.m

Jrfmdb

//

Created by jerehedu on 15/6/18.

Copyright (c) 2015 jerehedu. All rights reserved.

//

#import "ViewController.h"

#import "FMDatabase.h"

@interface Viewcontroller ()

@property (nonatomic, strong) Fmdatabase *db;

@end

@implementation Viewcontroller

-(void) viewdidload

{

[Super Viewdidload];

Import SQLite framework, Import Fmdb folder

1. Get the path to the database file

NSString *doc=[nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) lastObject];

NSString *filename=[doc stringbyappendingpathcomponent:@ "Student.sqlite"];

NSLog (@ "filename =%@", filename);

2. Access to the database

Fmdatabase *db = [Fmdatabase databasewithpath:filename];

3. Open the Database

if ([db Open]) {

NSLog (@ "OK");

4. Create a table

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 (@ "Success of the Table");

}else{

NSLog (@ "Create a table failure");

}

}

self.db=db;

Inserting data

[Self insertstu];

[Self deletestu:6];

[Self updatestu:@ "apple7_name": @ "7777"];

[Self querystu];

[Self dropstu];

[Self insertstu];

[Self querystu];

6. Close the database

[Self.db Close];

}

#pragma mark inserts data

-(void) Insertstu

{

for (int i=0; i<10; i++)

{

NSString *name = [NSString stringwithformat:@ "1apple%i_name", I];

int age = Arc4random ()%3+20;

1. Executeupdate: Indeterminate parameters are used for placeholder (the following parameters must all be OC objects)

[Self.db executeupdate:@ INSERT into t_student (name, age) VALUES (?,?); ", name,@ (age)];

2. Executeupdatewithformat: Indeterminate parameters are occupied with%@,%d, etc. (parameter is the original data type)

[self.db executeupdatewithformat:@ INSERT INTO t_student (name, age) VALUES (%@,%i); ", Name,age];

3. Array

[Self.db executeupdate:@ INSERT into t_student (name, age) VALUES (?,?); "withargumentsinarray:@[name,@ (age)]];

}

}

#pragma mark Deletes data

-(void) Deletestu: (int) Idnum

{

A. Executeupdate: Indeterminate parameters used to occupy the position (the following parameters must all be OC objects)

[Self.db executeupdate:@ "Delete from t_student where id=?;", @ (Idnum)];

B. Executeupdatewithformat: Indeterminate parameters are occupied by%@,%d, etc.

[Self.db executeupdatewithformat:@ "Delete from t_student where name=%@;", @ "Apple9_name"];

}

#pragma mark, destroy the form.

-(void) Dropstu

{

[Self.db executeupdate:@ "drop table if exists t_student;"];

4. Create a table

BOOL result=[self.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 (@ "Create a table again");

}else{

NSLog (@ "Create a table again failed");

}

}

#pragma mark modifies the data

-(void) Updatestu: (NSString *) Oldname:(nsstring*) newName

{

[self.db executeupdatewithformat:@ update t_student set name=%@ where name=%@; ", Newname,oldname];

[self.db executeupdate:@ update t_student set name=? Where Name=? ", Newname,oldname];

}

#pragma mark queries the data

-(void) Querystu

{

1. Execute Query statement

Fmresultset *resultset = [self.db executequery:@ "select * from T_student;"];

Fmresultset *resultset = [self.db executequery:@ "select * from t_student where ID

2. Traverse the result set

while ([ResultSet next]) {

int idnum = [ResultSet intforcolumn:@ "id"];

NSString *name = [resultSet objectforcolumnname:@ "name"];

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

NSLog (@ "id=%i, name=%@, age=%i", idnum,name,age);

}

}

-(void) didreceivememorywarning

{

[Super didreceivememorywarning];

Dispose of any of the can is recreated.

}

@end

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.