iOS原生sqlite的使用
首先导入数据库使用到的包
#import <sqlite3.h>
声明一个数据库
sqlite3 *db;
使用单例来管理数据库
+ (instancetype)shareDataBaseTool{
static DataBaseTool *tool;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
tool = [[DataBaseTool alloc] init];
});
return tool;
}
打开数据库
– (void)openDB{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *database = [paths objectAtIndex:0];
NSString *database_path = [database stringByAppendingPathComponent:@”manager.sqlite”];
if (sqlite3_open([database_path UTF8String], &db) != SQLITE_OK) {
sqlite3_close(db);
DLog(@”数据库打开失败”);
}else{
DLog(@”打开成功”);
}
}
打开数据库表
– (void)creatRepaireTable{
char *errmsg;
NSString *sqlStr = @”create table if not exists home(logId integer primary key autoincrement,managerId integer,name text,operation text,recordTime text)”;
if (sqlite3_exec(db,[sqlStr UTF8String], nil, nil, &errmsg) == SQLITE_OK) {
DLog(@”创建表成功”);
}else{
DLog(@”表创建失败”);
}
}
插入数据
– (void)insertRepaire:(KCLogsModel *)repairModel{
NSString *sqlStr = [NSString stringWithFormat:@”insert into home(logId,managerId,name,operation,recordTime)values(‘%tu’,’%tu’,’%@’,’%@’,’%@’)”,repairModel.logId,repairModel.managerId,repairModel.name,repairModel.operation,repairModel.recordTime];
if (sqlite3_exec(db, [sqlStr UTF8String], nil, nil, nil) == SQLITE_OK) {
DLog(@”添加成功”);
}else{
DLog(@”添加失败”);
}
}
查询数据
– (void)select{
NSString *sqlStr = @”select name,operation,recordTime from home where operation like ‘%添加%’ order by logId asc”;
NSMutableArray *modelArray = [NSMutableArray arrayWithCapacity:0];
sqlite3_stmt *stmt = NULL;
if (sqlite3_prepare_v2(db, [sqlStr UTF8String], -1, &stmt, NULL) == SQLITE_OK) {
while (sqlite3_step(stmt) == SQLITE_ROW) {
char *name = (char *)sqlite3_column_text(stmt, 0);
char *operation = (char *)sqlite3_column_text(stmt, 1);
char *recordTime = (char *)sqlite3_column_text(stmt, 2);
KCLogsModel *model = [[KCLogsModel alloc] init];
model.name = [NSString stringWithUTF8String:(char *)name];
model.operation = [NSString stringWithUTF8String:(char *)operation];
model.recordTime = [NSString stringWithUTF8String:(char *)recordTime];
DLog(@”%@ %@ %@”,model.name,model.operation,model.recordTime);
}
}
}
关闭数据库
– (void)closeDB{
sqlite3_close(db);
}