码迷,mamicode.com
首页 > 移动开发 > 详细

iOS sqlite3

时间:2016-08-14 13:01:03      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:

简介

sqlite是短小精悍的关系型数据库,常运用于嵌入式设备,麻雀虽小五脏俱全,能满足大部分数据存储的需求,目前使用最多的是sqlite3。

其语句不区分大小写,每条语句必须以分号(;)结尾 ,不可使用关键字对表和字段命名。

 

常用关键字有SELECT、INSERT、UPDATE、DELETE、CREATE、DROP、ALTER、TABLE、FROM、WHERE、SET、ORDER、BY、GROUP、HAVING、DESC、ASC、VIEW、INDEX、IF NOT EXISTS、LIMIT、LIKE,JOIN、LEFT JOIN、ON等等

 

虽然sqlite是不区分存储类型,甚至建表时都可以不设置类型,默认存储为字符串,但大致分为:

INTEGER(整型): int

REAL(浮点型): float, double

TEXT(字符串):char

BLOD(二进制数据)

 

sqlite常用约束条件有:

PRIMARY KEY (主键)

NOT NULL (非空)

UNIQUE (不重复)

FOREIGN KEY (外键)

CHECK (满足指定条件)

DEFAULT (给定默认值)

AUTOINCREMENT (字段为整型可自动加1)

 

SQL语句基本示例

create table if not exists test (id int primary key autoincrement name text, age integer default 1, address text not null);

crate table T2 as select id, name, age, address from T1 where 1=1;

drop table if exists test;

insert into test (name, age,address) values (‘jack‘,30,‘china‘);

update test set name = ‘LiMing‘, age = 32 where address = ‘china‘;

delete from test where name = ‘jack‘;

select * from test where name = ‘LiMing‘;

select * from test where name like ‘Li%‘;

select count(*) from test where name like ‘%M%‘;

select max(age) from test;

select min(age) from test;

select avg(age) from test;

select sum(age) from test;

select s.name, s.age, b.name as bookname, b.price from student s join book b on b.id = s.bookid;

 

 

iOS代码示例

 

#import <Foundation/Foundation.h>

@interface SQLiteManager : NSObject

+(instancetype)shareInstance;

-(NSError*)openDBWithName:(NSString*)name;

-(NSError*)openDBWithPath:(NSString*)path;

-(NSError*)updateWithSQL:(NSString*)sql;

-(NSArray*)queryWithSQL:(NSString*)sql;

@end

 

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

static SQLiteManager *instance;

@interface SQLiteManager ()

@property (nonatomic) sqlite3 *db;

@end

@implementation SQLiteManager

+(instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        if (!instance) {
            instance = [self allocWithZone:zone];
        }
    });
    
    return instance;
}

+(instancetype)shareInstance {
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        if (!instance) {
            instance = [[SQLiteManager alloc] init];
        }
    });
    return instance;
}

-(NSError*)openDBWithName:(NSString*)name {
    
    NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    
    NSString *path = [directory stringByAppendingPathComponent:name];
    
    return [self openDBWithPath:path];
}

-(NSError*)openDBWithPath:(NSString*)path {
    
    if (SQLITE_OK != sqlite3_open([path UTF8String], &_db)) {
        
        sqlite3_close(_db);
        
        return [NSError errorWithDomain:[NSString stringWithFormat:@"打开数据库失败:%@",path] code:-1 userInfo:nil];
        
    }
    
    return nil;
}

-(NSError*)updateWithSQL:(NSString*)sql {
    char *error;
    
    if (SQLITE_OK != sqlite3_exec(_db, [sql UTF8String], NULL, NULL, &error)) {
        
        return [NSError errorWithDomain:[NSString stringWithFormat:@"执行SQL语句失败:%@",sql] code:-1 userInfo:nil];
        
    }
    
    return nil;
}

-(NSArray*)queryWithSQL:(NSString*)sql {
    NSMutableArray *results = [[NSMutableArray alloc] init];
    
    sqlite3_stmt *stmt;
    
    if (SQLITE_OK == sqlite3_prepare_v2(_db, [sql UTF8String], -1, &stmt, NULL)) {
        
        while (SQLITE_ROW == sqlite3_step(stmt)) {
            
            int count = sqlite3_column_count(stmt);
            
            NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
            
            for (int i=0; i<count; i++) {
                
                NSString *key = [NSString stringWithUTF8String:sqlite3_column_name(stmt, i)];
                
                NSString *value = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, i)];
                
                [dic setValue:value forKey:key];
                
            }
            
            [results addObject:dic];
            
        }
        
    }
    
    sqlite3_finalize(stmt);
    
    return nil;
}

-(NSError*)insertData:(NSData*)data key:(NSString*)key{
    //create table if not exsts datatable (key text, data blod);
    NSString *sql = @"insert into datatable(key, data) values(?,?)";
    
    sqlite3_stmt *stmt;
    
    NSError *error = [NSError errorWithDomain:[NSString stringWithFormat:@"执行SQL语句失败:%@",sql] code:-1 userInfo:nil];
    
    if (SQLITE_OK != sqlite3_prepare_v2(_db, [sql UTF8String], -1, &stmt, NULL)) {
        return error;
    }
    
    sqlite3_bind_text(stmt, 1, [key UTF8String], -1, NULL);
    
    sqlite3_bind_blob(stmt, 2, data.bytes, (int)data.length, NULL);
    
    if (sqlite3_step(stmt) != SQLITE_DONE) {
        return error;
    }
    
    sqlite3_finalize(stmt);
    
    return nil;
}

-(NSError*)updateData:(NSData*)data key:(NSString*)key{
    //create table if not exsts datatable (key text, data blod);
    NSString *sql = [NSString stringWithFormat:@"update datatable set data = ? where key = %@",key];
    
    sqlite3_stmt *stmt;
    
    NSError *error = [NSError errorWithDomain:[NSString stringWithFormat:@"执行SQL语句失败:%@",sql] code:-1 userInfo:nil];
    
    if (SQLITE_OK != sqlite3_prepare_v2(_db, [sql UTF8String], -1, &stmt, NULL)) {
        return error;
    }
    
    sqlite3_bind_text(stmt, 1, [key UTF8String], -1, NULL);
    
    sqlite3_bind_blob(stmt, 2, data.bytes, (int)data.length, NULL);
    
    if (sqlite3_step(stmt) != SQLITE_DONE) {
        return error;
    }
    
    sqlite3_finalize(stmt);
    
    return nil;
}

-(NSArray*)queryDataWithSQL:(NSString*)sql {
    NSMutableArray *array = [NSMutableArray array];
    
    sqlite3_stmt *stmt;
    
    if (SQLITE_OK == sqlite3_prepare_v2(_db, [sql UTF8String], -1, &stmt, NULL)) {
        
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            
            NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
            
            const void *blod = sqlite3_column_blob(stmt, 1);
            
            int length = sqlite3_column_bytes(stmt, 1);
            
            NSData *data = [[NSData alloc] initWithBytes:blod length:length];
            
            [dic setValue:data forKey:[[NSString alloc] initWithUTF8String:(const char *)sqlite3_column_text(stmt, 0)]];
            
            [array addObject:dic];
        }
        
    }
    
    return array;
}

 

iOS sqlite3

标签:

原文地址:http://www.cnblogs.com/nmzd/p/5768146.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!