1. Archiving and database operations

Source: Internet
Author: User
Tags sqlite sqlite database

Archived operations

Role: Used primarily for the persistence of custom objects

Use: Comply with <nscoding Agreement >

-(void) Encodewithcoder: (Nscoder *) Acoder;

-(Nullable Instancetype) Initwithcoder: (Nscoder *) Adecoder;

1.sqlite3 the Use

1, to use SQLite3, first to add the library file libsqlite3.dylib

2. Import Header File

Import<sqlite3.h>

2.FMDB the introduction

1.FMDB is the sqlite Database Framework of the iOS platform, which encapsulates SQLite's C language API in OC mode, which is easier to use than simply invoking SQLite statements.

2.FMDB is more object-oriented , eliminating a lot of cumbersome, redundant C-language code

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

4. Provides a multi-threaded Secure database operation method to effectively prevent data confusion

If you want to use Fmdb

import "FMDB.h"

3. core three major categories

      • Fmdatabase (Create, delete)
        • A Fmdatabase object represents a single SQLite database
        • Used to execute SQL statements
      • Fmresultset (for query)
        • Result set after query execution with Fmdatabase
      • Fmdatabasequeue
        • Used to execute multiple queries or updates in multiple threads, which is thread-safe

4. steps to use

(1) Open the database

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

Fmdatabase *db = [Fmdatabase Databasewithpath:path];

if ([db Open]) {

//Database open successfully

}

2. Usage examples:

1. Get the path to the database file

nsstring *doc =[nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) lastObject];

2. Stitching file names

NSString *filename = [Doc stringbyappendingpathcomponent:@ "Status.sqlite"];

//3. Get the database

_db = [Fmdatabase databasewithpath:filename];

//4. Open the database. Use the following statement, if open fails, may be insufficient permissions or insufficient resources. Usually after you open the operation, you need to call the Close method to close the database. The database must be open before interacting with the database. Failure to open or create a database can cause open failures if resources or permissions are insufficient.

if ([_db Open]) {

//5. Create a table

BOOL result = [_db executeupdate:@ "CREATE TABLE IF not EXISTS t_home_status (ID integer PRIMARY KEY autoincrement, acc Ess_token text NOT NULL, STATUS_IDSTR text is not NULL, status_dict blob is not null); "];

if (result) {

NSLog (@ "Success Chart");

} else {

NSLog (@ "Failure to create a table");

}

null: Indicates that the value is a null value.

integer: unsigned integer value.

REAL: Floating-point value.

text: literal string, stored using the encoding method UTF-8, Utf-16be, Utf-16le.

blob: Stores blob data in exactly the same type of data as the input data.

3. Path settings:

1. If the path you set does not exist, it will be automatically created

2. If @ "" or nil, an empty database is created in the temp file and the database file is deleted when the database is closed

(2) perform insert :

Using the Fmdatabase class to perform a database insert command SQL "INSERT INTO"

1.executeupdate:oc [self.db executeupdate:@ "INSERT into T_student (name, age) VALUES (?,?); ', name,@ (age)];

//2.executeupdatewithforamat: Indeterminate parameters are occupied with%@,%d etc. (parameter is raw data type, execution statement is case insensitive)

[self.db executeupdatewithforamat:@ "INSERT into t_student (name,age) values (%@,%i);", Name,age];

//3. Parameters are how arrays are used

int age = 18;

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

(3) perform the deletion :

Use the Fmdatabase class to execute the database Delete command SQL "delete"

1. Unsure of the parameters to use? To placeholder (The following argument must be an OC object, and the int should be wrapped as an OC object)

int idnum = 101;

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

//2. Indeterminate parameters are occupied by%@,%d, etc.

[Self.db executeupdatewithformat:@ "t_student =%@;", @ "Apple_name"];

(4) Perform the update

Simply put, a command that does not start with a select is an update command.

1.create,drop,insert,update,delete, such as operations other than queries, are called update operations

2. Use the Executeupdate: method to do the update operation

      • -(BOOL) Executeupdate: (nsstring*) SQL, ...
      • -(BOOL) Executeupdatewithformat: (nsstring*) format, ...
      • -(BOOL) executeupdate: (nsstring) SQL Withargumentsinarray: (nsarray ) arguments
      • Write SQL statements in SQL string
      • Performs an update that returns a bool value. Yes indicates successful execution, otherwise it indicates an error. You can call the-lasterrormessage and-lasterrorcode methods to get more information.
    • 3. Using the example

[DB executeupdate:@ "UPDATE t_student_classtwo SET age =? WHERE name =?; ", @" @ "@" Stu "]

(5) execute the query

1. How to execute a database query : (Query using fmresultset object)

The Select command is the query, and the method to execute the query begins with-excutequery.

    • When the query is executed, the error returns nil if the Fmresultset object is successfully returned. Equivalent to performing an update, supports the use of the Nserror parameter.

    • -(Fmresultset ) ExecuteQuery: (NSString ) SQL, ...
    • -(Fmresultset ) Executequerywithformat: (nsstring) format, ...
    • -(Fmresultset ) ExecuteQuery: (nsstring ) SQL Withargumentsinarray: (Nsarray *) arguments
    • Use the next method of the Fmresultset object to traverse the queried data

Fmresultset ways to get different data formats

    • Intforcolumn:
    • Longforcolumn:
    • Longlongintforcolumn:
    • Boolforcolumn:
    • Doubleforcolumn:
    • Stringforcolumn:
    • Dataforcolumn:
    • Datanocopyforcolumn:
    • Utf8stringforcolumnindex:
    • Objectforcolumn:

2. Using the example

fmresultset *resultset = [self.db Execute query:@ "select * from T_student;"];

//Search by Criteria

Fmresultset *resultset = [self.db executequery:@ "select * from T_student where id<?;" @ (14)];

Sort queries

[_db executequery:@ "SELECT * from T_student ORDER BY age desc"], this is sorted by the age field descending order ascending is not write DESC

//Traverse result collection

while ([ResultSet next])

{

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

nsstring *name = [resultSet objectforcolumn:@ "name"];

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

}

(6) Database deletion

Use the Fmdatabase class to perform a database destruction command Sqldrop ...

[self.db executeupadate:@ "drop table if exists t_student;];

(7) thread-safe Database

To ensure thread safety, Fmdb provides quick and easy Fmdatabasequeue class

Example:

Queue = [Fmdatabasequeue Databasequeuewithpath:path];

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

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

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

fmresultset *results = [db executequery:@ "select * from T_student"];

While ([results next]) {

//...

}

}];

1. Archiving and database operations

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.