IOS SQLite Database

Source: Internet
Author: User

Brief introduction

Use SQLite in iOS to work with your data. If you already know SQL, you can easily master the operation of the SQLite database.

Instance steps

1. Create a simple view based application

2. Select the project file, then select the target, add the Libsqlite3.dylib library to the selection frame

3. Select Objective C class to create a new file by selecting "file-> New-File ...", click Next

4, "Sub Class of" Is NSObject ", class named Dbmanager

5. Select Create

6. Update the DBManager.h as shown below

#import <Foundation/Foundation.h> #import <sqlite3.h> @interface dbmanager:nsobject{    NSString * DatabasePath;} + (dbmanager*) getsharedinstance;-(BOOL) createdb;-(BOOL) SaveData: (nsstring*) registernumber name: (nsstring*) name   Department: (nsstring*) department Year: (nsstring*) year;-(nsarray*) Findbyregisternumber: (nsstring*) Registernumber; @end

7. Update the DBMANAGER.M as shown below

#import "DBManager.h" static DBManager *sharedinstance = nil;static sqlite3 *database = nil;static sqlite3_stmt *statement = Nil, @implementation dbmanager+ (dbmanager*) getsharedinstance{if (!sharedinstance) {sharedinstance = [[Super        Allocwithzone:null]init];    [Sharedinstance Createdb]; } return sharedinstance;}    -(BOOL) createdb{nsstring *docsdir;        Nsarray *dirpaths; Get the documents directory dirpaths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask        , YES);    Docsdir = Dirpaths[0]; Build the path to the database file DatabasePath = [[NSString alloc] initwithstring: [Docsdir STRINGBYAPPENDINGP    Athcomponent: @ "student.db"];    BOOL issuccess = YES;        Nsfilemanager *filemgr = [Nsfilemanager Defaultmanager];                if ([filemgr fileexistsatpath:databasepath] = = NO) {const char *dbpath = [DatabasePath utf8string]; if (Sqlite3_open (DBPath, &database) = = SQLITE_OK) {            Char *errmsg; const char *SQL_STMT = "CREATE table if not exists studentsdetail (Regno integer primary key, name                        Text, department text, year text) "; if (sqlite3_exec (database, sql_stmt, NULL, NULL, &AMP;ERRMSG)! = SQLITE_OK) {IsS                uccess = NO;            NSLog (@ "Failed to create TABLE");            } sqlite3_close (database);        return issuccess;            } else {issuccess = NO;        NSLog (@ "Failed to open/create database"); }} return issuccess;} -(BOOL) SaveData: (nsstring*) registernumber name: (nsstring*) Name Department: (nsstring*) department Year: (nsstring*) Year        {const char *dbpath = [DatabasePath utf8string]; if (Sqlite3_open (DBPath, &database) = = SQLITE_OK) {nsstring *insertsql = [NSString stringWithFormat : @ "INSERT into Studentsdetail (regno,name, Department, year) values        (\ "%d\", \ "%@\", \ "%@\", \ "%@\") ", [Registernumber IntegerValue], name, department, year];        const char *insert_stmt = [Insertsql utf8string];        SQLITE3_PREPARE_V2 (Database, insert_stmt,-1, &statement, NULL);        if (sqlite3_step (statement) = = Sqlite_done) {return YES;        } else {return NO;    } sqlite3_reset (statement); } return NO;        -(nsarray*) Findbyregisternumber: (nsstring*) registernumber{const char *dbpath = [DatabasePath utf8string];        if (Sqlite3_open (DBPath, &database) = = SQLITE_OK) {nsstring *querysql = [NSString stringWithFormat:                @ "SELECT name, department, year from Studentsdetail where regno=\"%@\ "", Registernumber];        const char *query_stmt = [Querysql utf8string];        Nsmutablearray *resultarray = [[Nsmutablearray alloc]init]; if (SQLITE3_PREPARE_V2 (database, query_stmt,-1, &statement, NULL) = = Sqlite_OK) {if (sqlite3_step (statement) = = Sqlite_row) {nsstring *n                AME = [[NSString alloc] initwithutf8string: (const char *) Sqlite3_column_text (statement, 0)];                [Resultarray Addobject:name]; NSString *department = [[NSString alloc] initwithutf8string: (const char *) Sqlite3_column_text (statement,                1)];                [Resultarray addobject:department];                NSString *year = [[NSString alloc]initwithutf8string: (const char *) Sqlite3_column_text (statement, 2)];                [Resultarray Addobject:year];            return resultarray;                } else{NSLog (@ "not found");            return nil;        } sqlite3_reset (statement); }} return nil;}

8. Update the Viewcontroller.xib file

9. Create iboutlets for the above text fields

10. Create ibaction for the above button

11, as shown below, update ViewController.h

#import <UIKit/UIKit.h> #import "DBManager.h" @interface viewcontroller:uiviewcontroller< uitextfielddelegate>{    iboutlet Uitextfield *regnotextfield;    Iboutlet Uitextfield *nametextfield;    Iboutlet Uitextfield *departmenttextfield;    Iboutlet Uitextfield *yeartextfield;    Iboutlet Uitextfield *findbyregisternumbertextfield;    Iboutlet Uiscrollview *myscrollview;} -(Ibaction) SaveData: (ID) sender;-(ibaction) FindData: (ID) sender; @end

12. Update the VIEWCONTROLLER.M as shown below

#import "ViewController.h" @interface Viewcontroller () @end @implementation viewcontroller-(ID) Initwithnibname: ( NSString *) Nibnameornil Bundle: (NSBundle *) nibbundleornil{self = [Super Initwithnibname:nibnameornil Bundle:nibbundl    Eornil]; if (self) {//Custom initialization} return to self;}    -(void) viewdidload{[Super Viewdidload]; Do any additional setup after loading the view from its nib.}    -(void) didreceivememorywarning{[Super didreceivememorywarning]; Dispose of any resources the can be recreated.}    -(Ibaction) SaveData: (ID) sender{BOOL success = NO;    NSString *alertstring = @ "Data insertion failed";    if (regnotextfield.text.length>0 &&nametextfield.text.length>0 && Departmenttextfield.text.length>0 &&yeartextfield.text.length>0) {success = [[DBManager getShare Dinstance]savedata:regnotextfield.text Name:nameTextField.text Department:departmentTextField.text Year:ye ArtextfielD.text];    } else{alertstring = @ "Enter all fields"; } if (success = = NO) {Uialertview *alert = [[Uialertview alloc]initwithtitle:alertstring Message:n        Il delegate:nil cancelbuttontitle:@ "OK" otherbuttontitles:nil];    [Alert show]; }}-(ibaction) FindData: (ID) sender{Nsarray *data = [[DBManager getsharedinstance]findbyregisternumber:findbyregister    Numbertextfield.text]; if (data = nil) {Uialertview *alert = [[Uialertview alloc]initwithtitle: @ "Data not found" Message:nil del        Egate:nil cancelbuttontitle: @ "OK" otherbuttontitles:nil];        [Alert show];        Regnotextfield.text = @ "";        Nametextfield.text [email protected] "";        Departmenttextfield.text = @ "";    Yeartextfield.text [email protected] "";        } else{regnotextfield.text = Findbyregisternumbertextfield.text;        Nametextfield.text =[data objectatindex:0]; Departmenttextfield.text = [Data objectatindEX:1];    Yeartextfield.text =[data Objectatindex:2]; }} #pragma mark-text field delegate-(void) textfielddidbeginediting: (Uitextfield *) textfield{[Myscrollview SetFrame:C    Grectmake (10, 50, 300, 200)]; [Myscrollview setcontentsize:cgsizemake (300, 350)];} -(void) textfielddidendediting: (Uitextfield *) textfield{[Myscrollview setframe:cgrectmake (10, 50, 300, 350)];}    -(BOOL) Textfieldshouldreturn: (Uitextfield *) textfield{[TextField Resignfirstresponder]; return YES;} @end
Output

Now when we run the application, we get the following output, where we can add and find student details

IOS SQLite Database

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.