Data storage in iOS

Source: Internet
Author: User
Tags sqlite database throw exception

  • SQLite3 is an open-source embedded relational database with good portability, ease of use, and low memory overhead.
  • SQLite3 is untyped, meaning that you can save any type of data to any field in any table.
  • SQLite3 Common 4 data types: text (text string), Integer (integer value), real (floating point value), BLOB (binary data (such as file)).
    To use SQLite3 in iOS, first add the library file ‘libsqlite3.dylib‘ and import the primary header file#import<sqlite3.h>

    Features of the SQL statement:

    1> is not case sensitive;
    2> Each statement must be separated by a semicolon ; End

    Commonly used in SQLKey Words:

    Pselect, INSERT, UPDATE, Delete, from, create, where, desc, order, by, Group, table, Alter, view, index, and so on
    You cannot use keywords to name tables, fields in a database.

    Types of SQL statements:

    1> data definition statement (ddl:data definition Language)
    Including create and drop operations;
    Creates a new table or deletes a table in the database (CREATE table or drop table).
    2> Data manipulation statements (Dml:data manipulation Language)
    Including INSERT, UPDATE, delete and other operations;
    The 3 actions above are used to add, modify, and delete data from a table.
    3> data query Statement (dql:data query Language)
    can be used to query to obtain the data in the table;
    The keyword Select is the most used operation for DQL (and all SQL);
    Other dql commonly used keywords are where,order by,group by and having to create.

    Create a table:

    create table if not exists t_student (id integer, name text, age inetger, score real) ;

    Delete table:

    drop table if exists t_student;

    Inserting data (insert):

    insert into t_student (name, age) values (‘JN‘, 22) ;
    Note: The string contents in the database should be enclosed in single quotes.

    Update data (Updata):

    pupdate t_student set name = ‘jack‘, age = 20 ;
    Note: The above update will change the name of all records in the T_student table to Jack,age to 20;

    Delete the data (delete):

    delete from t_student;
    All records in the T_student table will be deleted.
    If you want to update or delete only some of the fixed records, you must add some conditions to the DML statement. The example is as follows:

    // 将t_student表中年龄大于10 并且 姓名不等于jack的记录,年龄都改为 5  update t_student set age = 5 where age > 10 and name != ‘jack’ ; // 删除t_student表中年龄小于等于10 或者 年龄大于30的记录 delete from t_student where age <= 10 or age > 30 ;
    Query Statement (DQL):

    SELECT * from T_student where age > 10; Conditional query Condition statement:

    PRIMARY KEY constraint:

    Each table must have a primary key to identify the uniqueness of the record.
    What is the primary key:
    The primary key (Primary key, referred to as PK), is used to uniquely identify a record.
    For example, t_student can add an ID field as the primary key, which is equivalent to a person's ID.
    The primary key can be a field or multiple fields.

    FOREIGN KEY constraints:

    FOREIGN KEY constraints allow you to establish a connection between tables.
    The general case of a foreign key is that a field in one table refers to the primary key field of another table.

    Open, close the database

    To create or open a database:

    // path为:~/Documents/person.dbsqlite3 *db;int result = sqlite3_open([path UTF8String], &db);

    Code parsing:
    Sqlite3_open () will open the database based on the file path, and if it does not, a new database will be created. If result equals constant SQLITE_OK, the database is opened successfully.
    SQLite *db: An open db instance.
    The path to the database file must be passed in the C string, not nsstring.
    Close database: sqlite3_close (db);
    Executes an SQL statement that does not return a statement

    char *errorMsg;  // 用来存储错误信息char *sql = "create table if not exists t_person(id integer primary key autoincrement, name text, age integer);";int result = sqlite3_exec(db, sql, NULL, NULL, &errorMsg);

    Code parsing:
    Sqlite3_exec () can execute any SQL statements, such as Create, update, insert, and delete operations. However, it is generally not necessary to execute a query statement because it does not return the query to the data.
    Sqlite3_exec () can also execute the statement:
    1> Open transaction: begain transaction;

    SQLite Function Summary:
    1. Open the DatabaseIntSqlite3_open(ConstChar *filename,The file path of the database Sqlite3 **ppdbdatabase instance);2. Execute any SQL statementIntSqlite3_exec(sqlite3*,An open DB instanceConstChar *sql,SQL statements that need to be executedInt (*callback)(void*,Intchar**,char**),Callback after the SQL statement has completed executionvoid *,The 1th parameter of a callback functionChar **errmsgError message);3. Check the legality of the SQL statement (pre-query preparation)IntSqlite3_prepare_v2(Sqlite3 *db,DB instanceConstChar *zsql,SQL statements that need to be checkedint Nbyte,The maximum byte length of the SQL statement is sqlite3_stmt **ppstmt,SQLITE3_STMT instances to obtain database dataConstChar **pztail);4. Querying a row of dataIntSqlite3_step(sqlite3_stmt*);If a row of data is queried, the Sqlite_row is returned5. Use stmt to get the value of a field (the subscript of the field from0 start)DoubleSqlite3_column_double(sqlite3_stmt*,int icol);Floating point dataIntSqlite3_column_int(sqlite3_stmt*,int icol); //Integer data sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int icol); //long-integer data const void *Sqlite3_column_blob(sqlite3_stmt*, int icol); //Binary text data const unsigned char *sqlite3_column_text(sqlite3_stmt*, int icol); //String data                   

The Core data Framework provides an object-relational mapping (ORM) capability to convert OC objects into data, save them in a SQLite3 database file, and restore data saved in a database to OC objects. No SQL statements are required during the secondary data operation.

Use this feature to add coredata.framework and import the primary header file <coredate/coredata.h>.

Model files: In CoreData, the objects that need to be mapped are called entities (entity), and you need to use CoreData's model files to describe all the entity and entity properties of the app.


通过Core Data从数据库中取出的对象,默认情况下都是NSManagedObject对象. NSManagedObject的工作模式有点类似于NSDictionary对象,通过键-值对来存取所有的实体属性. setValue:forkey:存储属性值(属性名为key); valueForKey:获取属性值(属性名为key).

CoreData Main objects

NSManagedObjectContext:负责数据和应用库之间的交互(CRUD); NSPersistentStoreCoordinator:添加持久化存储库(比如SQLite数据库); NSManagedObjectModel:代表Core Data的模型文件; NSEntityDescription:用来描述实体;

Setting up CoreData Context:
To load a model file from an application packageNsmanagedobjectmodel *model = [Nsmanagedobjectmodel Mergedmodelfrombundles:NIL];Incoming model, initializingNspersistentstorecoordinatorNspersistentstorecoordinator *PSC = [[Nspersistentstorecoordinator alloc] Initwithmanagedobjectmodel:model];Build SQLite file pathNSString *docs = [Nssearchpathfordirectoriesindomains (NSDocumentDirectory,Nsuserdomainmask,YES) Lastobject];Nsurl *url = [Nsurl Fileurlwithpath:[docs stringbyappendingpathcomponent:@ ""];Add a persistent repository, where SQLite is used as the repositoryNserror *error =NilNspersistentstore *store = [PSC addpersistentstorewithtype:Nssqlitestoretype configuration:nil url:url options:nil error:&error];if (store = = nil) {//direct throw exception [nsexception raise:@" Add Database Error "Format:@"%@ ", [ Error localizeddescription]];} //initialization context, setting Persistentstorecoordinator properties nsmanagedobjectcontext Alloc] Init];context.persistentstorecoordinator = PSC; //used up, or to [context release]; /* persistent repository type: Nssqlitestoretype SQLite database nsbinarystoretype binary flat file Nsinmemorystoretype Memory Library, unable to persist data permanently although these 3 types of performance are similar in speed, the information that is retained from the data model is different in almost all scenarios, the default settings should be used, using SQLite as the Persistence repository */   
Add Data:
Incoming context, creating a person entity objectNsmanagedobject *person = [Nsentitydescription Insertnewobjectforentityforname:@ "Person" inmanagedobjectcontext:context];Set simple properties [person SetValue:@ "JN" Forkey:@ "name"]; [Person setvalue:[NSNumber Numberwithint:Forkey]:@ "Age"];Incoming context, creating a card entity objectNsmanagedobject *card = [nsentitydescription insertnewobjectforentityforname:@ "Card" inmanagedobjectcontext:context]; [Card setValue:@ "447640819" Forkey:@ "no"];  Sets the association relationship between person and card [person Setvalue:card forkey:@ "card"]; //Use context object to synchronize data to persistent repository nserror *error = nil;  BOOL success = [Context save:&error]; if (!success) {[nsexception raise:@ ' Access database error ' format:@ '%@ ', [Error localizeddescription]];} //If you want to do an update: if you call [context Save:&error] after changing the properties of the entity object, you can synchronize the changed data to the database        
Query data:
Initializing a query RequestNsfetchrequest *request = [[Nsfetchrequest alloc] init];Set the entity to queryNsentitydescription *desc = [Nsentitydescription Entityforname:@ "Person" inmanagedobjectcontext:context];Set sort (by age descending)Nssortdescriptor *sort = [Nssortdescriptor Sortdescriptorwithkey:@ "Age" ascending:No];request. sortdescriptors = [Nsarray Arraywithobject:sort];Set conditional filtering (name like '%jn-1% ')Nspredicate *predicate = [Nspredicate Predicatewithformat:@ "name like%@", @ "*jn-1*"];request. predicate = predicate; Note: When setting conditional filtering, the% in the database is used * to replace //execute requests Nserror *error = Nil;  Nsarray *OBJS = [Context executefetchrequest:request error:&error]; if (error) {[nsexception raise:@ "Query Error" format:@ "%@", [Error localizeddescription]];} //Traverse Data for (nsmanagedobject *obj in Objs) { NSLog (@ "name=%@", [obj Valueforkey:@ " Name "]}                 
Delete data:
// 传入需要删除的实体对象 [context deleteObject:managedObject];// 将结果同步到数据库NSError *error = nil; [context save:&error];if (error) {     [NSException raise:@"删除错误" format:@"%@",[error localizedDescription]];}
Deferred loading of Core data:
Core Data不会根据实体中的关联关系立即获取相应的关联对象;比如通过Core Data取出Person实体时,并不会立即查询相关联的Card实体,当应用真的需要使用Card时,才会查询数据库,加载Card实体信息.

To create a subclass of Nsmanagedobject:

By default, entities taken with core data are of type Nsmanagedobject and can access data using key-value pairs.

However, in general, when entities are accessing data and sometimes need to add some business methods to accomplish some other tasks, they must create nsmanagedobject subclasses.

// 那么生成一个Person实体对象就应该这样写 Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context]; = @"JN";person.age = [NSNumber numberWithInt:24];Card *card = [NSEntityDescription insertNewObjectForEntityForName:@”Card" inManagedObjectContext:context]; = @”447640819";person.card = card;

Data storage: Http:// from the author of Pnyg_

Data storage in iOS

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: 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.