iOS sqlite 增删改查 简单封装(基于 FMDB)
/**
* 对 sqlite 的使用进行简单封装,仅涉及简单的单表 增删改查
*
* 基于 FMDB
*
* 操作基于 model ,数据库表字段与 model 属性一一对应,对 model 整体进行操作
*
* 根据 model 对象自动建表,字段类型只支持 NSString , NSIteger , float
*
* 用到 runtime 运行时获取 model 属性
*
*/
//
// AGDatabaseManager.h
//
// Created by Ager on 15/11/10.
// Copyright © 2015年 Ager. All rights reserved.
// /**
* 对 sqlite 的使用进行简单封装,仅涉及简单的单表 增删改查
*
* 基于 FMDB
*
* 操作基于 model ,数据库表字段与 model 属性一一对应,对 model 整体进行操作
*
* 根据 model 对象自动建表,字段类型只支持 NSString , NSIteger , float
*
* 用到 runtime 运行时获取 model 属性
*
*/ #import <Foundation/Foundation.h> @interface AGDatabaseManager : NSObject + (AGDatabaseManager*)shareAGDatabaseManager; /**
* 创建表格
*
* @param cls model 类
* @param tbName 表名
* @param keyName 主键字段
* @param key 主键的属性设置
*
* @return 创建表格是否成功
*/
- (BOOL)creatTable:(Class)cls tableName:(NSString*)tbName keyName:(NSString*)keyName primaryKey:(NSString*) key; /**
* 向表格插入数据
*
* @param model 数据模型与数据库表格对应
* @param tbName 要操作的表名
*
* @return 添加是否成功
*/
- (BOOL)insert:(id)model tableName:(NSString*)tbName; /**
* 更新数据
*
* @param tbName 要操作的表名
* @param model 数据模型与数据库表格对应
* @param str 更新操作查要更新的数据的条件
*
* @return 更新是否成功
*/
- (BOOL)update:(id)model tableName:(NSString*)tbName where:(NSString*)str; /**
* 删除数据
*
* @param tbName 要删除数据的表名
* @param str 要删除的数据的查找条件
*
* @return 删除是否成功
*/
- (BOOL)deleteTableName:(NSString*)tbName where:(NSString*)str; /**
* 查询数据
*
* @param model 数据模型与数据库表格对应
* @param tbName 要操作的表名
* @param str 删除操作查要删除的数据的条件
*
* @return 查询结果 (数组每一项为字典)
*/
- (NSArray*)select:(Class)model tableName:(NSString*)tbName where:(NSString*)str; /**
* 查询全部数据
*
* @param model 数据模型与数据库表格对应
* @param tbName 要操作的表名
*
* @return 查询结果 (数组每一项为字典)
*/
- (NSArray*)selectALL:(Class)model tableName:(NSString*)tbName; @end
AGDatabaseManager.h
//
// AGDatabaseManager.m
//
// Created by Ager on 15/11/10.
// Copyright © 2015年 Ager. All rights reserved.
// #import "AGDatabaseManager.h"
#import "FMDatabase.h"
#import <objc/runtime.h> static FMDatabase *fmdb = nil; @implementation AGDatabaseManager - (instancetype)init{
if (self = [super init]) { static dispatch_once_t oneToken;
dispatch_once(&oneToken, ^{
NSString *document = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[];
NSString *filePath = [document stringByAppendingPathComponent:@"database.sqlite"];
NSLog(@"%@",document);
fmdb = [FMDatabase databaseWithPath:filePath]; });
}
return self;
} + (AGDatabaseManager*)shareAGDatabaseManager{
return [[AGDatabaseManager alloc]init];
} - (BOOL)creatTable:(Class)cls tableName:(NSString*)tbName keyName:(NSString*)keyName primaryKey:(NSString*) key{ NSArray *array = [self getModelAllProperty:cls];
NSMutableString *sql = [NSMutableString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (",tbName]; for (int i = ; i < array.count; i++) {
NSDictionary *dic = array[i];
[sql appendFormat:@"%@ %@ ",[dic objectForKey:@"name"],[dic objectForKey:@"type"]];
if(keyName != nil && [keyName isEqualToString:[dic objectForKey:@"name"]]){
[sql appendString:key];
}
if (i < array.count - ){
[sql appendString:@","];
}
} [sql appendString:@")"]; NSLog(@"创建表格: %@",sql); [fmdb open];
BOOL result = [fmdb executeUpdate:[sql copy]];
NSLog(@"创建表格:%@",result ? @"成功":@"失败");
[fmdb close];
return result;
} - (BOOL)insert:(id)model tableName:(NSString*)tbName{ NSArray *array = [self getModelAllProperty:[model class]]; NSMutableString *propertyStr = [[NSMutableString alloc]init];
NSMutableString *valuesStr = [[NSMutableString alloc]init]; for (int i = ; i < array.count; i++) {
NSDictionary *dic = array[i];
[propertyStr appendString:[dic objectForKey:@"name"]];
[valuesStr appendFormat:@"'%@'",[model valueForKey:[dic objectForKey:@"name"]]]; if (i < array.count - ){
[propertyStr appendString:@","];
[valuesStr appendString:@","];
}
}
NSMutableString *sql = [NSMutableString stringWithFormat:@"INSERT INTO %@ (%@) values (%@)",tbName,propertyStr ,valuesStr];
NSLog(@"添加数据 : %@",sql);
[fmdb open];
BOOL result = [fmdb executeUpdate:[sql copy]];
[fmdb close];
NSLog(@"添加数据:%@",result ? @"成功":@"失败"); return result;
} - (BOOL)update:(id)model tableName:(NSString*)tbName where:(NSString*)str{
NSArray *array = [self getModelAllProperty:[model class]];
NSMutableString *sql = [NSMutableString stringWithFormat:@"UPDATE %@ SET ",tbName]; for (int i = ; i < array.count; i++) {
NSDictionary *dic = array[i];
NSString *pro = [dic objectForKey:@"name"];
[sql appendFormat:@"%@ = '%@'",pro,[model valueForKey:pro]];
if (i < array.count - ){
[sql appendString:@","];
}
} [sql appendFormat:@" where %@",str]; NSLog(@"修改数据 : %@",sql);
[fmdb open];
BOOL result = [fmdb executeUpdate:[sql copy]];
[fmdb close];
NSLog(@"更新数据:%@",result ? @"成功":@"失败");
return result;
} - (BOOL)deleteTableName:(NSString*)tbName where:(NSString*)str{
NSString *sql = [NSString stringWithFormat:@"delete from %@ where %@",tbName,str];
NSLog(@"删除数据 : %@",sql);
[fmdb open];
BOOL result = [fmdb executeUpdate:sql];
[fmdb close];
NSLog(@"更新数据:%@",result ? @"成功":@"失败");
return result;
} - (NSArray*)select:(Class)model tableName:(NSString*)tbName where:(NSString*)str{
NSString *sql = [NSString stringWithFormat:@"select * from %@ where %@",tbName,str];
NSArray *array = [self getModelAllProperty:[model class]];
[fmdb open];
NSLog(@"查询数据 : %@",sql);
FMResultSet *set = [fmdb executeQuery:sql];
NSMutableArray *allArray = [[NSMutableArray alloc]init];
while ([set next]) {
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
for (int i = ; i < array.count; i++) {
NSDictionary *dic1 = array[i];
NSString *pro = [dic1 objectForKey:@"name"];
[dic setValue:[set stringForColumn:pro] forKey:pro];
}
[allArray addObject:dic];
} [set close];
[fmdb close];
return [allArray copy];
} - (NSArray*)selectALL:(Class)model tableName:(NSString*)tbName {
NSString *sql = [NSString stringWithFormat:@"select * from %@ ",tbName];
NSArray *array = [self getModelAllProperty:[model class]];
[fmdb open];
NSLog(@"查询数据 : %@",sql);
FMResultSet *set = [fmdb executeQuery:sql];
NSMutableArray *allArray = [[NSMutableArray alloc]init];
while ([set next]) {
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
for (int i = ; i < array.count; i++) {
NSDictionary *dic1 = array[i];
NSString *pro = [dic1 objectForKey:@"name"];
[dic setValue:[set stringForColumn:pro] forKey:pro];
}
[allArray addObject:dic];
} [set close];
[fmdb close];
return [allArray copy];
} #pragma mark --- 辅助方法 --- /**
* 获取 model 类全部的属性和属性类型
*
* @param cls model 类 class
*
* @return 返回 model 的属性和属性类型
*/
- (NSArray *)getModelAllProperty:(Class)cls{ unsigned int count = ;
objc_property_t *propertys = class_copyPropertyList(cls, &count);
NSMutableArray *array = [NSMutableArray array];
for (int i = ; i < count; i++) { objc_property_t property = propertys[i];
NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding]; NSString *type = [self getPropertyAttributeValue:property name:@"T"]; if ([type isEqualToString:@"q"]||[type isEqualToString:@"i"]) {
type = @"INTEGER";
}else if([type isEqualToString:@"f"] || [type isEqualToString:@"d"]){
type = @"FLOAT";
}else{
type = @"TEXT";
} NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:propertyName , @"name",type , @"type", nil]; [array addObject:dic]; }
free(propertys); return array.copy;
} /**
* 获取属性的特征值
*/ - (NSString*)getPropertyAttributeValue:(objc_property_t) pro name:(NSString*)name{ unsigned int count = ;
objc_property_attribute_t *attributes = property_copyAttributeList(pro, &count); for (int i = ; i < count; i++) {
objc_property_attribute_t attribute = attributes[i];
if (strcmp(attribute.name, name.UTF8String) == ) {
return [NSString stringWithCString:attribute.value encoding:NSUTF8StringEncoding];
}
}
free(attributes);
return nil;
} @end
AGDatabaseManager.m
iOS sqlite 增删改查 简单封装(基于 FMDB)的更多相关文章
- iOS SQLite 增删改查的封装(关系型)
在工程里导入libsqlite3.tbd库(Xcode 7) #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder &l ...
- iOS SQLite增删改查(简单应用)
// 注意: 在工程里导入libsqlite3.tbd库(Xcode7,如果Xcode7以下的版本则导入libsqlite3.dylib). #import <UIKit/UIKit.h> ...
- sqlite3增删改查简单封装
import sqlite3 class DBTool(object): def __init__(self): """ 初始化函数,创建数据库连接 "&quo ...
- android 入门 006(sqlite增删改查)
android 入门 006(sqlite增删改查) package cn.rfvip.feb_14_2_sqlite; import android.content.Context; import ...
- WPF MVVM+EF增删改查 简单示例(二) 1对1 映射
WPF MVVM+EF增删改查 简单示例(一)实现了对学生信息的管理. 现在需求发生变更,在录入学生资料的时候同时需要录入学生的图片信息,并且一名学生只能有一张图片资料.并可对学生的图片资料进行更新. ...
- iOS CoreData 增删改查详解
最近在学习CoreData, 因为项目开发中需要,特意学习和整理了一下,整理出来方便以后使用和同行借鉴.目前开发使用的Swift语言开发的项目.所以整理出来的是Swift版本,OC我就放弃了. 虽然S ...
- 安卓版php服务器的mysql数据库增删改查简单案例
界面: index.php文件: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "h ...
- jdbc增删改查进行封装
jdbc封装 1 dao (代码分层) com.aaa.dao 存放dao相关的类型 例如 StudentDAOImpl 处理 数据库的链接 存取数据 com.aaa.servlet 存放servle ...
- C#Sqlite增删改查
说到使用数据库的话,无非也就是对数据的增加,删除和修改以及查询.前文已经 创建好了程序,现在我们就可以来具体实现Sqlite的数据操作,增删改查. 第一步,创建连接字符串来连接数据库: private ...
随机推荐
- ios -- NSdata 与 NSString,Byte数组,UIImage 的相互转换(转)
1. NSData 与 NSStringNSData-> NSStringNSString *aString = [[NSString alloc] initWithData:adata enc ...
- MyBatis(3.2.3) - One-to-one mapping using nested ResultMap
We can get Student along with the Address details using a nested ResultMap as follows: <resultMap ...
- 每天一道LeetCode--172. Factorial Trailing Zeroes
Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in log ...
- SoftReference
本文介绍对象的强.软.弱和虚引用的概念.应用及其在UML中的表示. 1.对象的强.软.弱和虚引用 在JDK 1.2以前的版本中,若一个对象不被任何变量引用,那么程序就无法再使用这个对象.也就是说 ...
- shell脚本字符串截取的8种方法
假设有变量 var=http://www.aaa.com/123.htm. 1. # 号截取,删除左边字符,保留右边字符. echo ${var#*//} 其中 var 是变量名,# 号是运算符,*/ ...
- Java之绘制艺术图案
前面已经介绍过绘制方法.这里不再赘述. package com.caiduping; import java.awt.Color; import java.awt.Graphics; import j ...
- 229. Majority Element II My Submissions Question
Total Accepted: 23103 Total Submissions: 91679 Difficulty: Medium Given an integer array of size n, ...
- iOS - 基于蓝牙数据交换的环境监测(温度、湿度、光照、粉尘、噪声)
一.蓝牙外设的数据接收 二.App端显示获取数据
- vc++字符转换
测试环境: vs2008 开发语言:C++ #include <iostream>#include <windows.h>#include <string> // ...
- 用于主题检测的临时日志(594fb726-af0b-400d-b647-8b1d1b477d72 - 3bfe001a-32de-4114-a6b4-4005b770f6d7)
这是一个未删除的临时日志.请手动删除它.(f8322da6-c527-47fb-98d2-f12a7d814d19 - 3bfe001a-32de-4114-a6b4-4005b770f6d7)