Database of IOS Development (SQLite)

Source: Internet
Author: User

SQLite Embedded Database benefits:
1. Embedded database
2. Support events, no configuration required, no installation required, no administrator required
3. Support for most SQL92 standards
4. The complete database is saved in a file above the disk, the same database file can be used on different machines, the maximum support database to 2T
5. The entire system less than 30,000 lines, less than 250KB of memory consumption

Start using SQLite:
1. Introduction of header Files
2. Open the Database
3. Execute SQL command
4. Close the database

The following code shows the opening, closing, adding, deleting, finding, and modifying of the entire database.

Create a single example:

#import <foundation/foundation.h> @class Student; @interface databasehandle:nsobject//Create a single case + (Databasehandle * ) Sharedb; Get Documents Path-(NSString *) Documentspath; Open database-(void) opendb; Close Database-(void) closedb; CREATE table-(void) createtable; Insert information-(void) Insertstudent: (Student *) Stu; Modification Information-(void) updatemessage; Delete Information-(void) deleteMessage; Find All-(void) selectallstudent; Conditional lookup (example)-(void) Selectwithsex: (NSString *) sex; @end

#import "DataBaseHandle.h" #import <sqlite3.h> #import "Student.h"//Global Simple Interest object static Databasehandle *sharemodle = Nil ; @implementation Databasehandle#pragma Mark implements simple Interest + (Databasehandle *) sharedb{if (nil = = Sharemodle) {Sharemo    Dle = [[Databasehandle alloc] init]; } return sharemodle;} #pragma mark gets the documents path-(NSString *) documentspath{nsstring *documentpath = Nssearchpathfordirectoriesindomains (NS    Documentdirectory, Nsuserdomainmask, YES) [0]; return documentpath;} Introduce the framework before manipulating the data (SQL ... 3.0)//Declare the object of a database static sqlite3 *db = nil; #pragma mark open the database-(void) opendb{//Determine if the database is empty if (nil = = db) {/ /With Documents path splicing database storage path (get storage path) nsstring *dbpath = [[Self Documentspath] stringbyappendingstring:@ "/student.sqlite"]        ;        Open the database according to the path, if there is no database on that path, create a database automatically//Open database (syntax in C language) int result = Sqlite3_open (dbpath.utf8string, &db);        Determine if the database is open successfully if (result = = Sqlite_ok) {NSLog (@ "database opened successfully"); } ElSE {NSLog (@ "Database open failed");    }}} #pragma mark close the database-(void) closedb{int result = Sqlite3_close (db);        if (result = = SQLITE_OK) {//If the shutdown succeeds, set to Nill db = nil;    NSLog (@ "database shutdown succeeded");    } else {NSLog (@ "Database shutdown failed");    }} #pragma mark create table-(void) createtable{//To create a table, use the SQL statement. The SQL statement is present in the form of a string nsstring *createstring = @ "CREATE TABLE IF not EXISTS student (Sid INTEGER PRIMARY KEY AUTOINCR    Ement not NULL, sname text, ssex text, sage text) ";         Execute SQL statement int result = SQLITE3_EXEC (db, createstring.utf8string, NULL, NULL, NULL);    if (result = = Sqlite_ok) {NSLog (@ "CREATE table succeeded");    } else {NSLog (@ "Create failed"); }} #pragma mark insert information-(void) Insertstudent: (Student *) stu{//Prepare INSERT statement nsstring *insertstring = [NSString stringwithfor    mat:@ "INSERT into student (sname,ssex,sage) VALUES ('%@ ', '%@ ', '%@ ')", stu.name,stu.sex,stu.age]; EXECUTE statement int result = SQLITE3_EXEC (db, insertstring.utf8string, NULL,NULL, NULL);    if (result = = Sqlite_ok) {NSLog (@ "Insert succeeded");    } else {NSLog (@ "Insert failed"); }} #pragma mark modify data-(void) updatemessage{//Prepare to modify statement nsstring *undatastring = @ "UPDATE student SET ssex = ' female ', sname    = ' small Dream ' WHERE sid = 10 ";    int result = SQLITE3_EXEC (db, undatastring.utf8string, NULL, NULL, NULL);    if (result = = Sqlite_ok) {NSLog (@ "modified successfully");    } else {NSLog (@ "failed to modify");     }} #pragma mark delete data-(void) deletemessage{//Prepare to delete statement nsstring *deletestring = @ "Delete from student WHERE sid = 1";    int result = SQLITE3_EXEC (db, deletestring.utf8string, NULL, NULL, NULL);    if (result = = Sqlite_ok) {NSLog (@ "delete ok");    } else {NSLog (@ "Delete _no");    }} #pragma mark find All-(void) selectallstudent{//Prepare to find statement nsstring *selectall = @ "SELECT *from student";         Create adjoint pointer sqlite3_stmt *stmt = NIL;    Prepare to execute int result = Sqlite3_prepare (db, Selectall.utf8string,-1, &stmt, NULL); If(Result = = SQLITE_OK) {//loop execution until no lookup is complete while (sqlite3_step (stmt) = = Sqlite_row) {//Remove SID (No. 0 column) NSI            Nteger sid = Sqlite3_column_int (stmt, 0);            Remove sname (1th column) nsstring *sname = [NSString stringwithutf8string: (const char *) Sqlite3_column_text (stmt, 1)];  Remove Ssex (2nd column) NSString *ssex = [NSString stringwithutf8string: (const char *) Sqlite3_column_text (stmt,            2)];            Remove Sage (3rd column) NSString *sage = [NSString stringwithutf8string: (const char *) Sqlite3_column_text (stmt, 3)];         NSLog (@ "sid:%d sname:%@ ssex:%@ sage:%@", sid,sname,ssex,sage);    } sqlite3_finalize (stmt);        } else {//If lookup fails, end companion pointer sqlite3_finalize (stmt);    NSLog (@ "Find failed"); }} #pragma mark condition Lookup-(void) Selectwithsex: (NSString *) sex{//Prepare to find statement nsstring *selecststring = @ "SELECT * FROM St    Udent WHERE ssex =? ";    Create adjoint pointer sqlite3_stmt *stmt = NIL; Pre-Execute INT result = Sqlite3_prepare (db, Selecststring.utf8string,-1, &stmt, NULL); if (result = = SQLITE_OK) {//Binding? The value//"1" represents the first question mark "?" And which parameters bind Sqlite3_bind_text (stmt, 1, sex.        Utf8string,-1, NULL);            while (Sqlite3_step (stmt) = = Sqlite_row) {Nsinteger sid = Sqlite3_column_int (stmt, 0);            NSString *sname = [NSString stringwithutf8string: (const char *) Sqlite3_column_text (stmt, 1)];            NSString *ssex = [NSString stringwithutf8string: (const char *) Sqlite3_column_text (stmt, 2)];            NSString *sage = [NSString stringwithutf8string: (const char *) Sqlite3_column_text (stmt, 3)];        NSLog (@ "Sid:%d sname:%@ ssex:%@ Sage:%@", sid,sname,ssex,sage);        }} else {//close pointer sqlite3_finalize (stmt);    NSLog (@ "Query failed"); }} @end

Create a Student class
#import <foundation/foundation.h> @interface student:nsobject@property (nonatomic,strong) NSString *name;@ Property (Nonatomic,strong) NSString *age; @property (Nonatomic,strong) nsstring *sex; @end </foundation>
Viewdidload Call method in VIEWCONTROLLER.M
    Print path    NSLog (@ "%@", [[Databasehandle Sharedb] documentspath]);    Open Database    [[Databasehandle sharedb] opendb];    CREATE TABLE    [[Databasehandle sharedb] createtable];         Insert information//    Student *stu = [[Student alloc] init];//    stu.name = @ "small dew";//    Stu.age = @ "+";//    Stu.sex = @ "female";    [[Databasehandle sharedb] insertstudent:stu];    Modify//    [[Databasehandle sharedb] updatemessage];    Delete//    [[Databasehandle sharedb] deleteMessage];    Find all information//    [[Databasehandle sharedb] selectallstudent];    Find information by Condition    [[databasehandle Sharedb] selectwithsex:@ "female"];

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Database of IOS Development (SQLite)

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.