SQLite Simple to use

Source: Internet
Author: User
Tags sqlite

viewcontroller.m//sqlitedemo////Created by Lam_tt on 15-4-11.//Copyright (c) 2015 Lam_tt. All rights reserved.//#import "ViewController.h" #import <sqlite3.h> @interface Viewcontroller () {sqlite3 *_db;}    @end @implementation viewcontroller-(void) viewdidload {[Super viewdidload];    [Self opensqlite];    [Self Initbutton];    }-(void) Initbutton {nsarray *array = [Nsarray alloc]initwithobjects:@ "Add", @ "delete", @ "Change", @ "check", nil];        for (int i = 0; i < 4; i + +) {UIButton *button = [[UIButton alloc]init];        Button.bounds = CGRectMake (0, 0, 150, 30);        Button.tag = ten + i;        [Button settitle:array[i] forstate:uicontrolstatenormal];        Button.backgroundcolor = [Uicolor Graycolor];        [Button addtarget:self action: @selector (buttonpressed:) forcontrolevents:uicontroleventtouchupinside];        Button.center = Cgpointmake (Cgrectgetwidth (self.view.bounds)/2, + i * 50);    [Self.view Addsubview:button]; }} #pragma mark-button click Event-(VOID) buttonpressed: (UIButton *) Sender {Nsinteger index = sender.tag-10;            Switch (index) {case 0: [Self initinsertdata];                    Break            Case 1: [Self initdelete];        Break            Case 2: [Self initupdata];        Break            Case 3: [Self initselect];    Break    }} #pragma mark-create Database-(void) Opensqlite {//Sqlite3 *db;    Path NSString *string = [NSString stringwithformat:@ "%@/documents", Nshomedirectory ()];    NSString *filename = [string stringbyappendingstring:@ "/students.sqlite"];        oc-c const char *cfilename = filename.utf8string;        Open the database without automatically creating an int result = Sqlite3_open (cFileName, &_db);    if (result = = Sqlite_ok) {NSLog (@ "Successfully open database");    }else {NSLog (@ "Failed to open database"); }//Available Sqlitemanger view #pragma mark-Create table const char *sql= "CREATE table IF not EXISTS t_students (ID integer P Rimary KEY autoincrement,name Text not NULL,age integer not NULL); ";        char *errmsg = NULL; Parameters: The first parameter is the database handle (DB), the second parameter is the SQL statement, the third parameter is the callback parameter, is a pointer to the function, if the callback front of the * change to ^ is a block code snippet, the fourth parameter can write null,    The fifth parameter is an error message and is used for code debugging.        result = Sqlite3_exec (_db, SQL, NULL, NULL, &AMP;ERRMSG);    if (result = = Sqlite_ok) {NSLog (@ "CREATE table succeeded");    }else {printf ("Failed---%s----%s---%d", errmsg,__file__,__line__); }} #pragma mark-insert data-(void) Initinsertdata {for (int i = 0; i <; i + +) {//1. Splicing SQL statements NSSt                Ring *name = [NSString stringwithformat:@ "Data--%d", Arc4random_uniform (100)];                int age = Arc4random_uniform (20) + 10;                NSString *sql=[nsstring stringwithformat:@ "INSERT into T_students (name,age) VALUES ('%@ ',%d);", Name,age];        2. Execute SQL statement char *errmsg = NULL; Sqlite3_exec (_db, SQL.        Utf8string, NULL, NULL, &AMP;ERRMSG);        if (errmsg) {//If there is an error message NSLog (@ "Insert data failed--%s", errmsg);  }else {NSLog (@ "Insert data success");      }}} #pragma mark-select query operation-(void) Initselect {//From this table find the data const char *sql= "Sele    CT id,name,age from t_students WHERE age<20; ";        sqlite3_stmt *stmt = NULL; Prepare to work if (SQLITE3_PREPARE_V2 (_db, SQL,-1, &stmt, NULL) = = SQLITE_OK) {//sql Statement no problem NSLog (@ "S        QL Statement No problem "); Each time the Sqlite_step function is called, the stmt points to the next record while (Sqlite3_step (stmt) = = Sqlite_row) {//Take out data//(1) Remove the            0 column field get value (int type value) int ID = Sqlite3_column_int (stmt, 0);            (2) Take out the 2nd column field value (text type value) Const unsigned char *name = Sqlite3_column_text (stmt, 1);            (3) Remove the 2nd column field value int = Sqlite3_column_int (stmt, 2);        printf ("%d%s%d\n", id,name,age);    }}else {NSLog (@ "query statement has a problem, or no data");    }} #pragma mark-delete data-(void) initdelete {const char *sql = "Delete from t_students";    char *errmsg = NULL; Sqlite3_exec (_db, SQL, NULL, NULL, &errmsg);    if (errmsg) {NSLog (@ "Delete failed");    }else {NSLog (@ "Delete succeeded");    }}-(void) initupdata {const char *sql = "Update t_students set name = ' Xiaoming ', age = 16;";    char *errmsg = NULL;    Sqlite3_exec (_db, SQL, NULL, NULL, &AMP;ERRMSG);    if (errmsg) {NSLog (@ "failed to modify");    }else {NSLog (@ "modified successfully"); }} @end

Note: To import libsqlite3.dylib

SQLite Simple to use

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.