ios数据库sqlite3简单使用示例一

//
//  ViewController.m
//  TestSaveData
//
//  Created by cy on 14/12/21.
//  Copyright (c) 2014年 cy. All rights reserved.
//

#import "ViewController.h"
#import <sqlite3.h>

@interface ViewController (){
    sqlite3 *database;
}
@end

@implementation ViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self openDB];
    [self createTable];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)closeDB{
    sqlite3_close(database);
}

- (IBAction)add:(UIButton *)sender {
    NSString *name = _tfName.text;
    int age = [_tfAge.text intValue];
    [self addDataToDB:name andAge:age];
}

- (IBAction)query:(UIButton *)sender {
    [self queryDB];
}


-(void)openDB{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"person"];
    NSLog(@"path=%@",path);
    if(sqlite3_open([path UTF8String], &database)!=SQLITE_OK){
        sqlite3_close(database);
        NSAssert(0, @"database open failed");
    }
}

-(void)createTable{
//    NSString *sql = @"CREATE TABLE IF NOT EXISTS 'Person' (ID INTEGER PRIMARY KEY AUTOINCREMENT, 'Name' TEXT, 'Age' INTEGER);";
     NSString *sql = @"CREATE TABLE IF NOT EXISTS 'Person' ('Name' TEXT, 'Age' INTEGER);";
    char *errorMsg;
    if(sqlite3_exec(database, [sql UTF8String], NULL, NULL, &errorMsg)!=SQLITE_OK){
        sqlite3_close(database);
        NSAssert(0, @"create table failed , errorMsg:%s",errorMsg);
    }
}

-(void)addDataToDB:(NSString *)name andAge:(int)age{
    char *insert = "INSERT OR REPLACE INTO PERSON(NAME,AGE)""VALUES(?,?);";
    sqlite3_stmt *stmt;
    
    if(sqlite3_prepare_v2(database, insert, -1, &stmt, nil) ==SQLITE_OK){
       // sqlite3_bind_int(stmt, 1, NULL);
        sqlite3_bind_text(stmt, 1, [name UTF8String], -1, nil);
        sqlite3_bind_int(stmt, 2, age);
    }
    if(sqlite3_step(stmt)!=SQLITE_DONE){
        NSAssert(0,@"INSERT ERROR");
    }
    sqlite3_finalize(stmt);
}

-(void)deleteDataFromDB{
    
}

-(void)queryDB{
    char *sql = "SELECT NAME,AGE FROM PERSON";
    sqlite3_stmt *stmt;
    if(sqlite3_prepare_v2(database, sql, -1, &stmt, nil)==SQLITE_OK){
        while(sqlite3_step(stmt)==SQLITE_ROW){
            //int id = sqlite3_column_int(stmt, 1);
            char *name = (char *)sqlite3_column_text(stmt, 0);
            NSString *nameString = [[NSString alloc] initWithUTF8String:name];
            int age = sqlite3_column_int(stmt, 1);
            NSLog(@"%@,%d;\r\n",nameString,age);
        }
        sqlite3_finalize(stmt);
    }
}


@end

你可能感兴趣的:(ios数据库sqlite3简单使用示例一)