网上的数据封装类都很复杂也不太容易修改,自己简单封装了一个数据库类
需要用的数据库是SQLite
话不多说上代码 先是.h文件
#import <Foundation/Foundation.h>
@interface DataBaseHandle : NSObject
+ (instancetype)shareDataBaseHandle;
- (void)open:(NSString *)file;
- (void)closeDB;
- (void)updateSQL:(NSString *)SQL;
- (NSArray *)selectAllWithList:(NSString *)list AndListNumber:(NSInteger)num;
@end
接下来是.m文件
#import "DataBaseHandle.h"
#import <sqlite3.h>
@implementation DataBaseHandle
/** 创建单例数据库 */
+ (instancetype)shareDataBaseHandle {
static DataBaseHandle *dataBase = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dataBase = [DataBaseHandle new];
});
return dataBase;
}
sqlite3 *db;
- (void)open:(NSString *)file {
if (db) {
NSLog(@"数据库已开启!!!");
return;
}
int result = sqlite3_open(file.UTF8String, &db);
if (result == SQLITE_OK) {
NSLog(@"数据库打开成功!");
}else {
NSLog(@"数据库打开失败!,code = %d", result);
}
}
- (void)closeDB {
int result = sqlite3_close(db);
if (result == SQLITE_OK) {
NSLog(@"数据库关闭成功");
db = nil;
}else {
NSLog(@"数据库关闭失败.code:%d", result);
}
}
//增/删/改
- (void)updateSQL:(NSString *)SQL {
int result = sqlite3_exec(db, SQL.UTF8String, nil, nil, nil);
if (result == SQLITE_OK) {
NSLog(@"成功!");
}else {
NSLog(@"失败!.code:%d", result);
}
}
- (NSArray *)selectAllWithList:(NSString *)list AndListNumber:(NSInteger)num {
NSMutableArray *arr = [NSMutableArray new];
// SQL语句
NSString *selectSQL = [NSString stringWithFormat:@"SELECT * FROM %@ order by number desc", list];
//声明一个stmt对象(结构体)
sqlite3_stmt *stmt = nil;
int result = sqlite3_prepare_v2(db, selectSQL.UTF8String, -1, &stmt, nil);
if (result == SQLITE_OK) {
// 每行都执行查询语句
while (sqlite3_step(stmt) == SQLITE_ROW) {
//如果查询条件匹配.通过sqlite3_column函数簇 取出值.
NSMutableArray *tempArr = [[NSMutableArray alloc] init];
for (int i = 0 ; i < num; i++) {
const unsigned char *str = sqlite3_column_text(stmt, i);
[tempArr addObject:[NSString stringWithUTF8String:(const char *)str]];
}
[arr addObject:tempArr];
[tempArr release];
}
//销毁对象.
sqlite3_finalize(stmt);
}else {
NSLog(@"不能正常查询.code:%d", result);
//销毁对象.
sqlite3_finalize(stmt);
}
return arr;
}
@end
接下来是调用的方法
先设置打开的数据库路径,再设置语句,增、删、改都用一个命令updateSQL
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"historyDB.sqlite"];
[[DataBaseHandle shareDataBaseHandle] open:file];
//创建SQL语句.
NSString *createTableSQL = @"CREATE TABLE IF NOT EXISTS history(number INTEGER PRIMARY KEY AUTOINCREMENT, content text)";
[[DataBaseHandle shareDataBaseHandle] updateSQL:createTableSQL];
添加语句也是一样用updateSQL方法
NSString *SQL = [NSString stringWithFormat:@"insert into history(content) values('%@')", self.textFieldOfSearch.text];
[[DataBaseHandle shareDataBaseHandle] updateSQL:SQL];
查询方法我返回了一个二维数组比如arr[0][0]
第一个0是表示第几条数据
第二个0表示这一条数据的第几个数据
比如数据是((1,张三, 男), (2, 李四, 女) )
arr[1][2]就能提取"女"
NSArray *result = [[DataBaseHandle shareDataBaseHandle] selectAllWithList:@"history" AndListNumber:2];
查询语句中第一个参数是表名,第二个数据是查询每一条数据有几列