您的位置:首页 > 数据库

基于 iOS SQLite 增删改查基本方法的封装---通用式数据库访问类

2016-02-27 15:10 661 查看
1.本文使用iOS 对sqlite的基本操作进行封装,可以自动生成拼接SQL语句,自动绑定数据并执行,简化了数据库的四项主要操作,减少代码量。

首先看下使用样例,新建一个单视图工程,引入所需头文件"WDGDatabaseTool.h"(所需文件见附件),注意添加libsqlite3.0.tbd到工程中。


//
//  ViewController.m
//  WDGSqliteTool
//
//  Created by Wdgfnhui on 16/2/26.
//  Copyright © 2016年 Wdgfnhui. All rights reserved.
//

#import "ViewController.h"
#import "WDGDatabaseTool.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

//创建表(只需要调用一次就行啦,如果表已经存在可以不调用)
[WDGDatabaseTool creatTableWithSQL:@"CREATE TABLE if not exists student (id integer PRIMARY KEY AUTOINCREMENT,name text NOT NULL,age integer)"];

//根据表名获取一个WDGDatabaseTool的对象
WDGDatabaseTool *studentHandler = [WDGDatabaseTool DBManageWithTableName:@"student"];
//打开数据库
[studentHandler openDatabase];

//用字典插入一行数据 注意,每次运行程序都会插入数据
[studentHandler insertDataWithDictionary:@{@"name" : @"lisi", @"age" : @(20)}];
//用字典插入一行数据...
[studentHandler insertDataWithDictionary:@{@"name" : @"lisi", @"age" : @(19)}];
[studentHandler insertDataWithDictionary:@{@"name" : @"lisi", @"age" : @(18)}];
[studentHandler insertDataWithDictionary:@{@"name" : @"lisi", @"age" : @(17)}];
[studentHandler insertDataWithDictionary:@{@"name" : @"lisi", @"age" : @(16)}];
[studentHandler insertDataWithDictionary:@{@"name" : @"zhangsan", @"age" : @(18)}];
[studentHandler insertDataWithDictionary:@{@"name" : @"zhangsan", @"age" : @(17)}];
[studentHandler insertDataWithDictionary:@{@"name" : @"zhangsan", @"age" : @(16)}];

[studentHandler insertDataWithDictionary:@{@"name" : @"wangwu", @"age" : @(16)}];

//生成一个where条件
WDGWhereCondition *selectCondition = [WDGWhereCondition conditionWithColumnName:@"name" Operator:@"=" Value:@"lisi"];
//增加复合条件
[selectCondition addWhereConditionWithRelation:@"and" ColumnName:@"age" Operator:@"=" Value:@(18)];
//根据条件查询,获取查询结果,用数组接收
NSArray *selectResult = [studentHandler selectDataWithWhereCondition:selectCondition];
NSLog(@"%@", selectResult);

//生成一个where条件
WDGWhereCondition *deleteCondition = [WDGWhereCondition conditionWithColumnName:@"name" Operator:@"=" Value:@"wangwu"];
//根据条件删除
if ([studentHandler deleteDataWithWhereCondition:deleteCondition])
NSLog(@"删除成功");
else
NSLog(@"删除失败");

//生成一个where条件
WDGWhereCondition *updateCondition = [WDGWhereCondition conditionWithColumnName:@"name" Operator:@"=" Value:@"lisi"];
//根据条件和给定数据更新
if ([studentHandler updateDataWithNewData:@{@"name" : @"lisi2", @"age" : @(19)} WhereCondition:updateCondition])
NSLog(@"修改成功");
else
NSLog(@"修改失败");

//查询所有数据
NSLog(@"%@", [studentHandler selectAllData]);

/****给查询加排序等操作******/
//按照姓名降序排序并且按照年龄升序排序
[studentHandler orderWithDictionary:@{@"name" : @"desc", @"age" : @"asc"}];
//只获取前五行数据
[studentHandler limitForRows:5];

//    //从第2行开始获取5行数据
//    [studentHandler limitAtIndex:2 Rows:5];
NSLog(@"%@", [studentHandler selectAllData]);//按照上面的排序和行数现在查询
/***查询完成,order条件和limit条件只对紧跟着的查询生效***/

//上面的可以简化为连贯操作
NSLog(@"%@", [[[studentHandler orderWithDictionary:@{@"name" : @"desc"}] limitAtIndex:0 Rows:5] selectAllData]);

[studentHandler selectWithFields:@[@"name"] Condition:nil];//只查询姓名列

[studentHandler closeDatabase];//注意用完关闭数据库

// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end


这里已增加为例子说下对应方法的实现

- (BOOL)insertDataWithDictionary:(NSDictionary *)dataDic {//需要给字典参数
NSArray *allKeys = [dataDic allKeys];
NSMutableString *sql = [NSMutableString stringWithFormat:@"insert into %@(", self.tableName];//开始准备SQL语句
long lessOneCount = allKeys.count - 1;
int p = 0;
for (p = 0; p < lessOneCount; p++) {
[sql appendFormat:@"%@,", allKeys[p]];//根据传入参数进行SQL语句拼接
}
[sql appendFormat:@"%@) values(", allKeys[p]];
for (p = 0; p < lessOneCount; p++) {
[sql appendFormat:@"?,"];
}
[sql appendString:@"?)"];
STMT *stmt = NULL;
int result = sqlite3_prepare(db, sql.UTF8String, -1, &stmt, NULL);
if (result == OK) {
for (int i = 0; i < allKeys.count; i++) {
[self bindDataWithSTMT:stmt Order:i + 1 Value:dataDic[allKeys[i]] Type:_tableStuct[allKeys[i]][0]];//根据传入数据进行数据绑定
}
BOOL flag = sqlite3_step(stmt) == DONE;
sqlite3_finalize(stmt);
return flag;
}
sqlite3_finalize(stmt);
return false;
}


其实鄙人的想法很简单,就是在iOS操作数据库的方法的基础上,对SQL语句进行自动生成。

使用的大致步骤

导入附件中的文件(需要libsqlite3.0.tbd的支持)

在WDGDatabaseTool.h配置数据库名称(有则直接使用,无则创建空库)

在需要调用的地方引入WDGDatabaseTool.h头文件

如果时已存在的库并且库不为空,通过要操作的表名获取实例(不要自己alloc)

通过4中的实例对象调用相应方法,先打卡数据库

最后唠叨一句记着用完后关闭数据库,别的地方用时再打开

现在属于起步阶段,功能比较基本,不过还挺实用,日后会增加新的功能,欢迎大家来喷!

如有BUG小伙伴门可以自己改一下或者告诉我哈。

3月7日更新

修复若干bug

增加指定字段查询功能

增加order排序功能

增加limit限制功能

增加验证功能,当调用给定字段,条件等不合法是会抛出异常,防止继续运行而造成数据混乱

3月18日更新

修复了由于字段名大小写引起的查询失败(注意SQL表名,字段名大小写不敏感)

3月21日更新

增加调试模式,开启后可以输出每次操作对应的SQL语句(类方法调用 openDebugMode开启)

增加了对调用给定数据的类型验证

增加了对表是否存在的验证,抛出对应的异常

注意要用ARC,ARC,ARC

查询结果返回结果中的字典键均为小写,请亲们注意。

更新后下载链接如下

下载链接:http://download.csdn.net/detail/wdgfnhui/9468492
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: