sqlite数据库完整

//业务处理层.h文件

//首先导入数据库头文件 类头文件

#import <sqlite3.h>

#import “Model.h”

@interface LoadData : NSObject

//全局变量

{

sqlite3 *ss;

}

//单例类

+(instancetype)initShaertData;

//打开数据库

-(void)initOpenData;

//添加

-(void)addData:(Model *)mm;

//查询

-(NSMutableArray *)getAllData;

//关闭

-(void)close;

@end

//业务处理层.m文件 也是sqlite数据方法实现的界面

#import “LoadData.h”

////静态指针

static LoadData *ld = nil;

@implementation LoadData

//单例类

+(instancetype)initShaertData{

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

ld = [[LoadData alloc]init];

});

return ld;

}

+(instancetype)allocWithZone:(struct _NSZone *)zone{

if (!ld) {

ld = [super allocWithZone:zone];

}

return ld;

}

-(id)copy{

return self;

}

-(id)mutableCopy{

return self;

}

//打开数据库

-(void)initOpenData{

NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];

NSString *newpath = [path stringByAppendingPathComponent:@”sy.db”];

NSLog(@”new == %@”,newpath);

if (sqlite3_open([newpath UTF8String],&(ss)) == SQLITE_OK) {

NSLog(@”打开了”);

[self initTable];

}

}

//初始化数据库

-(void)initTable{

const char *sql = “create table if not exists zoo(id intager primary key, imgName text,img BLOB)”;

sqlite3_stmt *stmt;

sqlite3_prepare(ss, sql, -1, &stmt, nil);

sqlite3_step(stmt);

sqlite3_finalize(stmt);

}

//添加数据库

-(void)addData:(Model *)mm{

const char *sql = “insert into zoo values(null,?,?)”;

sqlite3_stmt *stmt;

sqlite3_prepare(ss, sql, -1, &stmt, nil);

sqlite3_bind_text(stmt, 1, [mm.imgName UTF8String], -1, SQLITE_TRANSIENT);

sqlite3_bind_text(stmt, 2, [mm.img bytes],  (int)[mm.img length], SQLITE_TRANSIENT);

if (sqlite3_step(stmt) == SQLITE_DONE) {

NSLog(@”添加成功”);

}

sqlite3_finalize(stmt);

}

//查询数据库

-(NSMutableArray *)getAllData{

const char *sql = “select *from zoo”;

sqlite3_stmt *stmt;

sqlite3_prepare(ss, sql, -1, &stmt, nil);

NSMutableArray *arr = [[NSMutableArray alloc]init];

while (sqlite3_step(stmt) == SQLITE_ROW) {

Model *mm = [[Model alloc]init];

mm.imgName = [NSString stringWithUTF8String:(const char *) sqlite3_column_text(stmt, 1)];

mm.img = [NSData dataWithBytes:sqlite3_column_blob(stmt, 2) length:sqlite3_column_bytes(stmt, 2)];

[arr addObject:mm];

}

sqlite3_finalize(stmt);

return arr;

}

//关闭数据库

-(void)close{

sqlite3_close(ss);

}

@end

Model.h层文件定义属性

@property(nonatomic,strong)NSString *imgName;

@property(nonatomic,strong)NSData *img;

    原文作者:leaderleader
    原文地址: https://www.jianshu.com/p/41507125f62a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞