时间:2021-07-01 10:21:17 帮助过:24人阅读
.m文件
//
// DbUtils.m
// smart
//
// Created by 谢厂节 on 15/5/12.
// Copyright (c) 2015年 WHR. All rights reserved.
//
#import "DbUtils.h"
#import "KMTypes.h"
#import "KMContents.h"
@implementation DbUtils
//打开数据库的方法
- (void)openDB{
///文件是否存在
NSFileManager* fileManager = [NSFileManager defaultManager];
NSString *dbpath=[self filePath];
NSLog(@"database path:%@",dbpath);
BOOL success = [fileManager fileExistsAtPath:dbpath];
if (!success) {
NSString *resourcePath=[[NSBundle mainBundle]resourcePath];
//自动复制
NSString *sourceDBPath=[resourcePath stringByAppendingPathComponent:@"app.bundle/datas.sqlite"];
NSError *error;
success = [fileManager copyItemAtPath:sourceDBPath toPath:dbpath error:&error];
if(!success)
NSAssert1(0,@"数据库附加失败!‘%@‘.", [error localizedDescription]);
else
NSLog(@"数据库附加成功:%@",dbpath);
}
if (sqlite3_open([[self filePath] UTF8String], &db) != SQLITE_OK) {
sqlite3_close(db);
NSAssert(0, @"数据库打开失败。");
}
}
- (void)closeDB{
sqlite3_close(db);
}
//该方法用于返回数据库在Documents文件夹中的全路径信息
- (NSString *)filePath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"datas.sqlite"];
}
////查询数据所有类别
- (NSMutableArray *)getAllTypes{
[self openDB];
NSMutableArray *array=[NSMutableArray arrayWithCapacity:6 ];
NSString *sql = @"SELECT * FROM km_types";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
KMTypes* k= [[KMTypes alloc]init];
int type_id = (int)sqlite3_column_int(statement,0);
int parent_id = (int)sqlite3_column_int(statement,1);
char *type_title = (char *)sqlite3_column_text(statement, 2);
int type_order = (int)sqlite3_column_int(statement,3);
int topic_count=(int)sqlite3_column_int(statement,4);
NSString *type_titleStr = [[NSString alloc] initWithUTF8String:type_title];
k.type_title = type_titleStr;
k.type_id=type_id;
k.parent_id = parent_id;
k.type_order = type_order;
k.topic_count=topic_count;
[array addObject:k];
}
sqlite3_finalize(statement);
}
[self closeDB];
return array;
}
@end
这里只实现一个简单的查询功能。
Mac 下使用sqlite3命令行
标签:sqlite3 ios ios6