iOS sqlite3

简介

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;
}

 

转载于:https://www.cnblogs.com/nmzd/p/5768146.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值