Simple use of the database for iOS development

Source: Internet
Author: User

Database Basics:

Plist:writetofile, Condition: Only one object has this method to use plist storage, and the custom object cannot be stored with plist
Preference: Preferences storage: Nsuserdefault storage, Benefits: No need to care about file name, fast storage, bottom: Just use a dictionary to do the storage. Cons: Before iOS8, you have to do a synchronous operation for the purpose of synchronizing the memory and the hard disk.
Nscoding (Nskeyedarchiver\nskeyedunarchiver): With a custom object archive, custom objects need to be archived: comply with the Nscoding protocol, and implement a corresponding method that tells the system which attributes need to be archived and which attributes need to be unpacked

SQLite3: Benefits: 1. Accurate reading of data 2. Fast query to the data you want 3. Can read data in bulk (you can read only a subset of the data)
Use occasion: 1. Used for offline cache (read-only to show data, can save traffic)

Local storage: Both are stored as files.
Database: exists in the form of a file
Database First step: Create a database file
Step two: Create a table--Define a model class
The third step: Design the design of the field (which properties are in this table)--the properties of the model (mainly depends on which properties you want to store)
Note: You will need a primary key, a unique identifier for each record, to automatically grow
Fourth step: Add records (set values for each property), create a model, and assign a value to the model

1. Creating a database link is equivalent to creating a database file

SQL statements
DDL statements: Creating tables and deleting tables
1. Create table if not EXISTS table name (field name segment Type,...);
CREATE table t_student (ID integer primary key,name text,age integer);
Judging if there's no this form
CREATE table if not exists t_student (ID integer primary key,name text,age integer);
2. Delete the table drop table if exists name;
drop table if exists t_student;
DML: Increase, delete, change: operation is record
Add insert into table name (field,...) VALUES (field values);
If the field is a string type, you must use single quotation marks (') to extend the
Insert into t_student (name,age) VALUES (' a ', 10);

Change the Update table name set field = field value,....
Update t_student Set name = ' C ', age = 18;
Delete: All records in T_student will be deleted
Delete from t_student;

Delete the From table name, and remove all records from the table.

3. Conditional statements
Update T_student Set age = 9 where the age =1 and name = ' Aterazawa ';

4. Query statement (DQL) Select field from table name;
Select S.name t_name from t_student s where age = 1 and name = ' Ozawa ';


Fuzzy query
%: Represents all values
% 3: Front no matter what value, just end with 3 OK
3%: No matter what the value, as long as 3 is OK
%3%: No matter what is in front of you, you can have a value or no value, as long as you have 3.
113:

First step: Create a database file

1. Import Sqlite3 Frame

2. Import Header File

3. Create a database file

1NSString *docpatch = Nssearchpathfordirectoriesindomains (Nsdocumentationdirectory, NSUserDomainMask, YES) [0];2NSString *filepatch = [Docpatch stringbyappendingpathcomponent:@"Student.splite"];3     /**4 * Open Database5      *6 * @param filename7 * @param ppdb8      *9 * If the @return is successful, the database file will be created automatically if it is successfully opened, the file name is filename, and the database instance will be assigned a valueTen      */ One     //Sqlite3_open (< #const char *filename#>, < #sqlite3 **ppdb#>) A     //Convert a string in OC to a C string, nsutf8string -Sqlite3 *db; -     if(Sqlite3_open (filepatch.utf8string, &db)) { theNSLog (@"Open Success"); -}Else{ -NSLog (@"Open Failed"); -}

Second, create a table statement

1 //Create a table2         /**3 * Execute database statements4          *5 * @param sqlite3 DB instance6 * @param SQL SQL statements7 * @param callback execution of the completed callback8 void * The first parameter of a callback9 errmsg error messageTen          * One * @return If the execution succeeds will return A          */ -         //sqlite3_exec (sqlite3 *, const char *sql, int (*callback) (void *, int, char * *, char * *), void *, char **errmsg); -         Char*errmsg; theNSString *sql =@"Crate table if not exists t_student (ID integer primary key, name text not null);"; -         //Create a table -  -Sqlite3 *db;
SQLITE3_EXEC (DB, SQL. Utf8string, NULL, NULL, &errmsg); + if(errmsg) { -NSLog (@"failed to create table"); +}Else { ANSLog (@"CREATE TABLE Success"); at}

Three, increase-insert (increase) The data of the statement

Char *errmsg;         *sql = [NSString stringWithFormat:@ "insert INTO t_student (name) VALUES (' abc '); " ];     // Create a table
    Sqlite3 *db;    SQLITE3_EXEC (DB, SQL. Utf8string, NULL, NULL, &errmsg);         if (errmsg) {        NSLog (@ " insert failed ");    } Else {        NSLog (@ " Insert succeeded ");    }

Iv. Deleting-delete a table statement

Char*errmsg; NSString*sql = [NSString stringWithFormat:@"Delete from t_student;"]; //Create a table
Sqlite3 *db;
SQLITE3_EXEC (DB, SQL. Utf8string, NULL, NULL, &errmsg); if(errmsg) {NSLog (@"Delete Failed"); }Else{NSLog (@"Delete succeeded"); }

V.-Change the statement of a field in a table

Char*errmsg; NSString*sql = [NSString stringWithFormat:@"Update t_student Set name = ' B ';"]; //Create a tableSqlite3 *db;    
SQLITE3_EXEC (DB, SQL. Utf8string, NULL, NULL, &errmsg); if(errmsg) {NSLog (@"Update failed"); }Else{NSLog (@"Update Successful"); }

Vi. Check-Find data statements

Query and additions and deletions are not the same, the query must first have a preparation, first look at the query Statement C language function

1 //Query and additions and deletions change the same2     3     //1. Prepare your data4     /**5      *6      *7 * DB: Data instance8 * Zsql: Prepared statement for query9 the byte -1-> of the INT nbyte query statement will automatically calculate the bytesTen ppstmt: Handle: The record inside the operation database OneReturn value is ready to returnSQLITE_OK, failed to returnSqlite_fail A      */ -SQLITE3_PREPARE_V2 (Sqlite3 *db,Const Char*zsql,intNbyte, Sqlite3_stmt **ppstmt,Const Char**pztail)

Query Statement Code Instance

1SQLITE3_STMT *stmt;2Sqlite3 *db;3NSString *sql = [NSString stringWithFormat:@"select * from T_student;"];4     if(SQLITE3_PREPARE_V2 (DB, SQL.) Utf8string,-1, &stmt, NULL) = = SQLITE_OK) {5NSLog (@"ready to succeed");6         //execute a handle to find the next record7          while(Sqlite3_step (stmt) = =Sqlite_row) {8NSLog (@"Find Data");9             //get which column of dataTen             ConstUnsignedChar*name = Sqlite3_column_text (stmt,1); OneStudent *s =[[Student alloc] init]; AS.name = [NSString stringwithutf8string: (Const Char*) name]; - [Arrm addobject:s]; -         } the          -          -}

Simple use of the database for iOS development

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.