ios常用數據庫
直接copy過去就能用,我們不用再去造輪子,現在的xocod9.4更賤人性化了,不用再添加依賴庫,這點蘋果你讓我滿意了,哈哈、
需要這兄弟拉進去的哈
下班標的1,2,3,4就是就截圖的4個文件,沒毛病老鐵。。。??
[TestDBModel clearTable]; //清空數據庫
NSLog(@"前[TestDBModel findAll]=%@",[TestDBModel findAll]);
NSArray *arr1 = @[@"哈哈",@"嘻嘻",@"呵呵"];
NSMutableArray *mArr = [[NSMutableArray alloc] init];
for (int i = 0; i < arr1.count; i++) {
TestDBModel *test = [[TestDBModel alloc] init];
test.name = arr1[i];
if (i==1) {
test.sexNum = 100;
test.isDoctor = YES;
}else{
test.sexNum = i;
test.isDoctor = NO;
}
[mArr addObject:test];
}
[TestDBModel saveObjects:mArr];
NSLog(@"後[TestDBModel findAll]=%@",[TestDBModel findAll]);
===================1
//
// DBHelper.h
// Doctor
//
// Created by zrq on 15/10/8.
// Copyright ? 2015年 zrq. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "FMDB.h"
@interface DBHelper : NSObject
@property (nonatomic, retain, readonly) FMDatabaseQueue *dbQueue;
+ (DBHelper *)shareInstance;
+ (NSString *)dbPath;
- (BOOL)changeDBWithDirectoryName:(NSString *)directoryName;
@end
===================2
//
// DBHelper.m
// Doctor
//
// Created by zrq on 15/10/8.
// Copyright ? 2015年 zrq. All rights reserved.
//
#import "DBHelper.h"
#import "DBModel.h"
#import <objc/runtime.h>
@interface DBHelper()
@property (nonatomic, retain) FMDatabaseQueue *dbQueue;
@end
@implementation DBHelper
static DBHelper *_instance = nil;
+ (instancetype)shareInstance
{
static dispatch_once_t onceToken ;
dispatch_once(&onceToken, ^{
_instance = [[super allocWithZone:NULL] init] ;
}) ;
return _instance;
}
+ (NSString *)dbPathWithDirectoryName:(NSString *)directoryName
{
NSString *docsdir = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSFileManager *filemanage = [NSFileManager defaultManager];
if (directoryName == nil || directoryName.length == 0) {
docsdir = [docsdir stringByAppendingPathComponent:@"ZrqDB"];
} else {
docsdir = [docsdir stringByAppendingPathComponent:directoryName];
}
BOOL isDir;
BOOL exit =[filemanage fileExistsAtPath:docsdir isDirectory:&isDir];
if (!exit || !isDir) {
[filemanage createDirectoryAtPath:docsdir withIntermediateDirectories:YES attributes:nil error:nil];
}
// NSString *dbpath = [docsdir stringByAppendingPathComponent:[NSString stringWithFormat:@"D%@.sqlite",UDString(DOCTOR_ID)]];
NSString *dbpath = [docsdir stringByAppendingPathComponent:[NSString stringWithFormat:@"D255.sqlite"]];
return dbpath;
}
+ (NSString *)dbPath
{
return [self dbPathWithDirectoryName:nil];
}
- (FMDatabaseQueue *)dbQueue
{
if (_dbQueue == nil) {
_dbQueue = [[FMDatabaseQueue alloc] initWithPath:[self.class dbPath]];
}
return _dbQueue;
}
- (BOOL)changeDBWithDirectoryName:(NSString *)directoryName
{
if (_instance.dbQueue) {
_instance.dbQueue = nil;
}
_instance.dbQueue = [[FMDatabaseQueue alloc] initWithPath:[DBHelper dbPathWithDirectoryName:directoryName]];
int numClasses;
Class *classes = NULL;
numClasses = objc_getClassList(NULL,0);
if (numClasses >0 )
{
classes = (__unsafe_unretained Class *)malloc(sizeof(Class) * numClasses);
numClasses = objc_getClassList(classes, numClasses);
for (int i = 0; i < numClasses; i++) {
if (class_getSuperclass(classes[i]) == [DBModel class]){
id class = classes[i];
[class performSelector:@selector(createTable) withObject:nil];
}
}
free(classes);
}
return YES;
}
+ (id)allocWithZone:(struct _NSZone *)zone
{
return [DBHelper shareInstance];
}
- (id)copyWithZone:(struct _NSZone *)zone
{
return [DBHelper shareInstance];
}
#if ! __has_feature(objc_arc)
- (oneway void)release
{
}
- (id)autorelease
{
return _instance;
}
- (NSUInteger)retainCount
{
return 1;
}
#endif
@end
===================3
//
// DBModel.h
// Doctor
//
// Created by zrq on 15/10/8.
// Copyright ? 2015年 zrq. All rights reserved.
//
#import <Foundation/Foundation.h>
/** SQLite五種數據類型 */
#define SQLTEXT @"TEXT"
#define SQLINTEGER @"INTEGER"
#define SQLREAL @"REAL"
#define SQLBLOB @"BLOB"
#define SQLNULL @"NULL"
#define PrimaryKey @"primary key"
#define primaryId @"pk"
@interface DBModel : NSObject
/** 主鍵 id */
@property (nonatomic, assign) int pk;
/** 列名 */
@property (retain, readonly, nonatomic) NSMutableArray *columeNames;
/** 列類型 */
@property (retain, readonly, nonatomic) NSMutableArray *columeTypes;
/**
* 獲取該類的所有屬性
*/
+ (NSDictionary *)getPropertys;
/** 獲取所有屬性,包括主鍵 */
+ (NSDictionary *)getAllProperties;
/** 數據庫中是否存在表 */
+ (BOOL)isExistInTable;
/** 表中的字段*/
+ (NSArray *)getColumns;
/** 保存或更新
* 如果不存在主鍵,保存,
* 有主鍵,則更新
*/
- (BOOL)saveOrUpdate;
/** 保存單個數據 */
- (BOOL)save;
/** 批量保存數據 */
+ (BOOL)saveObjects:(NSArray *)array;
/** 更新單個數據 */
- (BOOL)update;
/** 批量更新數據*/
+ (BOOL)updateObjects:(NSArray *)array;
/** 刪除單個數據 */
- (BOOL)deleteObject;
/** 批量刪除數據 */
+ (BOOL)deleteObjects:(NSArray *)array;
/** 通過條件刪除數據 */
+ (BOOL)deleteObjectsByCriteria:(NSString *)criteria;
/** 通過條件刪除 (多參數)--2 */
+ (BOOL)deleteObjectsWithFormat:(NSString *)format, ...;
/** 清空表 */
+ (BOOL)clearTable;
/** 查詢全部數據 */
+ (NSArray *)findAll;
/** 通過主鍵查詢 */
+ (instancetype)findByPK:(int)inPk;
/** 通過條件查詢 */
+ (instancetype)findFirstWithFormat:(NSString *)format, ...;
/** 查找某條數據 */
+ (instancetype)findFirstByCriteria:(NSString *)criteria;
+ (NSArray *)findWithFormat:(NSString *)format, ...;
/** 通過條件查找數據
* 這樣可以進行分頁查詢 @" WHERE pk > 5 limit 10"
*/
+ (NSArray *)findByCriteria:(NSString *)criteria;
/**
* 創建表
* 如果已經創建,返回YES
*/
+ (BOOL)createTable;
#pragma mark - must be override method
/** 如果子類中有一些property不需要創建數據庫字段,那麽這個方法必須在子類中重寫
*/
+ (NSArray *)transients;
@end
===================4
//
// DBModel.m
// Doctor
//
// Created by zrq on 15/10/8.
// Copyright ? 2015年 zrq. All rights reserved.
//
#import "DBModel.h"
#import <objc/runtime.h>
#import "DBHelper.h"
@implementation DBModel
#pragma mark - override method
+ (void)initialize
{
if (self != [DBModel self]) {
[self createTable];
}
}
- (instancetype)init
{
self = [super init];
if (self) {
NSDictionary *dic = [self.class getAllProperties];
_columeNames = [[NSMutableArray alloc] initWithArray:[dic objectForKey:@"name"]];
_columeTypes = [[NSMutableArray alloc] initWithArray:[dic objectForKey:@"type"]];
}
return self;
}
#pragma mark - base method
/**
* 獲取該類的所有屬性
*/
+ (NSDictionary *)getPropertys
{
NSMutableArray *proNames = [NSMutableArray array];
NSMutableArray *proTypes = [NSMutableArray array];
NSArray *theTransients = [[self class] transients];
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList([self class], &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
//獲取屬性名
NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
if ([theTransients containsObject:propertyName]) {
continue;
}
[proNames addObject:propertyName];
//獲取屬性類型等參數
NSString *propertyType = [NSString stringWithCString: property_getAttributes(property) encoding:NSUTF8StringEncoding];
/*
各種符號對應類型,部分類型在新版SDK中有所變化,如long 和long long
c char C unsigned char
i int I unsigned int
l long L unsigned long
s short S unsigned short
d double D unsigned double
f float F unsigned float
q long long Q unsigned long long
B BOOL
@ 對象類型 //指針 對象類型 如NSString 是@“NSString”
64位下long 和long long 都是Tq
SQLite 默認支持五種數據類型TEXT、INTEGER、REAL、BLOB、NULL
因為在項目中用的類型不多,故只考慮了少數類型
*/
if ([propertyType hasPrefix:@"T@"]) {
[proTypes addObject:SQLTEXT];
} else if ([propertyType hasPrefix:@"Ti"]||[propertyType hasPrefix:@"TI"]||[propertyType hasPrefix:@"Ts"]||[propertyType hasPrefix:@"TS"]||[propertyType hasPrefix:@"TB"]) {
[proTypes addObject:SQLINTEGER];
} else {
[proTypes addObject:SQLREAL];
}
}
free(properties);
return [NSDictionary dictionaryWithObjectsAndKeys:proNames,@"name",proTypes,@"type",nil];
}
/** 獲取所有屬性,包含主鍵pk */
+ (NSDictionary *)getAllProperties
{
NSDictionary *dict = [self.class getPropertys];
//NSLog(@"該類所有屬性:%@",[self.class getPropertys]);
NSMutableArray *proNames = [NSMutableArray array];
NSMutableArray *proTypes = [NSMutableArray array];
[proNames addObject:primaryId];
[proTypes addObject:[NSString stringWithFormat:@"%@ %@",SQLINTEGER,PrimaryKey]];
[proNames addObjectsFromArray:[dict objectForKey:@"name"]];
[proTypes addObjectsFromArray:[dict objectForKey:@"type"]];
//NSLog(@"%@",[NSDictionary dictionaryWithObjectsAndKeys:proNames,@"name",proTypes,@"type",nil]);
return [NSDictionary dictionaryWithObjectsAndKeys:proNames,@"name",proTypes,@"type",nil];
}
/** 數據庫中是否存在表 */
+ (BOOL)isExistInTable
{
__block BOOL res = NO;
DBHelper *jkDB = [DBHelper shareInstance];
[jkDB.dbQueue inDatabase:^(FMDatabase *db) {
NSString *tableName = NSStringFromClass(self.class);
res = [db tableExists:tableName];
}];
return res;
}
/** 獲取列名 */
+ (NSArray *)getColumns
{
DBHelper *jkDB = [DBHelper shareInstance];
NSMutableArray *columns = [NSMutableArray array];
[jkDB.dbQueue inDatabase:^(FMDatabase *db) {
NSString *tableName = NSStringFromClass(self.class);
FMResultSet *resultSet = [db getTableSchema:tableName];
while ([resultSet next]) {
NSString *column = [resultSet stringForColumn:@"name"];
[columns addObject:column];
}
}];
return [columns copy];
}
/**
* 創建表
* 如果已經創建,返回YES
*/
+ (BOOL)createTable
{
__block BOOL res = YES;
DBHelper *jkDB = [DBHelper shareInstance];
[jkDB.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
NSString *tableName = NSStringFromClass(self.class);
NSString *columeAndType = [self.class getColumeAndTypeString];
//NSLog(@"columeAndType= %@",columeAndType);
NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(%@);",tableName,columeAndType];
if (![db executeUpdate:sql]) {
res = NO;
*rollback = YES;
return;
};
NSMutableArray *columns = [NSMutableArray array];
FMResultSet *resultSet = [db getTableSchema:tableName];
while ([resultSet next]) {
NSString *column = [resultSet stringForColumn:@"name"];
[columns addObject:column];
}
NSDictionary *dict = [self.class getAllProperties];
NSArray *properties = [dict objectForKey:@"name"];
NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)",columns];
//過濾數組
NSArray *resultArray = [properties filteredArrayUsingPredicate:filterPredicate];
for (NSString *column in resultArray) {
NSUInteger index = [properties indexOfObject:column];
NSString *proType = [[dict objectForKey:@"type"] objectAtIndex:index];
NSString *fieldSql = [NSString stringWithFormat:@"%@ %@",column,proType];
NSString *sql = [NSString stringWithFormat:@"ALTER TABLE %@ ADD COLUMN %@ ",NSStringFromClass(self.class),fieldSql];
if (![db executeUpdate:sql]) {
res = NO;
*rollback = YES;
return ;
}
}
}];
return res;
}
/**
* 創建表
* 如果已經創建,返回YES
*/
//+ (BOOL)createTable
//{
// FMDatabase *db = [FMDatabase databaseWithPath:[JKDBHelper dbPath]];
// if (![db open]) {
// NSLog(@"數據庫打開失敗!");
// return NO;
// }
//
// NSString *tableName = NSStringFromClass(self.class);
// NSString *columeAndType = [self.class getColumeAndTypeString];
// NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(%@);",tableName,columeAndType];
// if (![db executeUpdate:sql]) {
// return NO;
// }
//
// NSMutableArray *columns = [NSMutableArray array];
// FMResultSet *resultSet = [db getTableSchema:tableName];
// while ([resultSet next]) {
// NSString *column = [resultSet stringForColumn:@"name"];
// [columns addObject:column];
// }
// NSDictionary *dict = [self.class getAllProperties];
// NSArray *properties = [dict objectForKey:@"name"];
// NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)",columns];
// //過濾數組
// NSArray *resultArray = [properties filteredArrayUsingPredicate:filterPredicate];
//
// for (NSString *column in resultArray) {
// NSUInteger index = [properties indexOfObject:column];
// NSString *proType = [[dict objectForKey:@"type"] objectAtIndex:index];
// NSString *fieldSql = [NSString stringWithFormat:@"%@ %@",column,proType];
// NSString *sql = [NSString stringWithFormat:@"ALTER TABLE %@ ADD COLUMN %@ ",NSStringFromClass(self.class),fieldSql];
// if (![db executeUpdate:sql]) {
// return NO;
// }
// }
// [db close];
// return YES;
//}
- (BOOL)saveOrUpdate
{
id primaryValue = [self valueForKey:primaryId];
if ([primaryValue intValue] <= 0) {
return [self save];
}
return [self update];
}
- (BOOL)save
{
NSString *tableName = NSStringFromClass(self.class);
NSMutableString *keyString = [NSMutableString string];
NSMutableString *valueString = [NSMutableString string];
NSMutableArray *insertValues = [NSMutableArray array];
for (int i = 0; i < self.columeNames.count; i++) {
NSString *proname = [self.columeNames objectAtIndex:i];
if ([proname isEqualToString:primaryId]) {
continue;
}
[keyString appendFormat:@"%@,", proname];
[valueString appendString:@"?,"];
id value = [self valueForKey:proname];
if (!value) {
value = @"";
}
[insertValues addObject:value];
}
[keyString deleteCharactersInRange:NSMakeRange(keyString.length - 1, 1)];
[valueString deleteCharactersInRange:NSMakeRange(valueString.length - 1, 1)];
DBHelper *jkDB = [DBHelper shareInstance];
__block BOOL res = NO;
[jkDB.dbQueue inDatabase:^(FMDatabase *db) {
NSString *sql = [NSString stringWithFormat:@"INSERT INTO %@(%@) VALUES (%@);", tableName, keyString, valueString];
res = [db executeUpdate:sql withArgumentsInArray:insertValues];
self.pk = res?[NSNumber numberWithLongLong:db.lastInsertRowId].intValue:0;
NSLog(res?@"插入成功":@"插入失敗");
}];
return res;
}
/** 批量保存用戶對象 */
+ (BOOL)saveObjects:(NSArray *)array
{
NSLog(@"BD保存002==>[DBModel class]= %@",[DBModel class]);
//判斷是否是JKBaseModel的子類
for (DBModel *model in array) {
if (![model isKindOfClass:[DBModel class]]) {
return NO;
}
}
__block BOOL res = YES;
DBHelper *jkDB = [DBHelper shareInstance];
// 如果要支持事務
[jkDB.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
for (DBModel *model in array) {
NSString *tableName = NSStringFromClass(model.class);
NSMutableString *keyString = [NSMutableString string];
NSMutableString *valueString = [NSMutableString string];
NSMutableArray *insertValues = [NSMutableArray array];
for (int i = 0; i < model.columeNames.count; i++) {
NSString *proname = [model.columeNames objectAtIndex:i];
if ([proname isEqualToString:primaryId]) {
continue;
}
[keyString appendFormat:@"%@,", proname];
[valueString appendString:@"?,"];
id value = [model valueForKey:proname];
if (!value) {
value = @"";
}
[insertValues addObject:value];
}
[keyString deleteCharactersInRange:NSMakeRange(keyString.length - 1, 1)];
[valueString deleteCharactersInRange:NSMakeRange(valueString.length - 1, 1)];
NSString *sql = [NSString stringWithFormat:@"INSERT INTO %@(%@) VALUES (%@);", tableName, keyString, valueString];
BOOL flag = [db executeUpdate:sql withArgumentsInArray:insertValues];
model.pk = flag?[NSNumber numberWithLongLong:db.lastInsertRowId].intValue:0;
NSLog(flag?@"插入成功":@"插入失敗");
if (!flag) {
res = NO;
*rollback = YES;
return;
}
}
}];
return res;
}
/** 更新單個對象 */
- (BOOL)update
{
DBHelper *jkDB = [DBHelper shareInstance];
__block BOOL res = NO;
[jkDB.dbQueue inDatabase:^(FMDatabase *db) {
NSString *tableName = NSStringFromClass(self.class);
id primaryValue = [self valueForKey:primaryId];
if (!primaryValue || primaryValue <= 0) {
return ;
}
NSMutableString *keyString = [NSMutableString string];
NSMutableArray *updateValues = [NSMutableArray array];
for (int i = 0; i < self.columeNames.count; i++) {
NSString *proname = [self.columeNames objectAtIndex:i];
if ([proname isEqualToString:primaryId]) {
continue;
}
[keyString appendFormat:@" %@=?,", proname];
id value = [self valueForKey:proname];
if (!value) {
value = @"";
}
[updateValues addObject:value];
}
//刪除最後那個逗號
[keyString deleteCharactersInRange:NSMakeRange(keyString.length - 1, 1)];
NSString *sql = [NSString stringWithFormat:@"UPDATE %@ SET %@ WHERE %@ = ?;", tableName, keyString, primaryId];
[updateValues addObject:primaryValue];
res = [db executeUpdate:sql withArgumentsInArray:updateValues];
NSLog(res?@"更新成功":@"更新失敗");
}];
return res;
}
/** 批量更新用戶對象*/
+ (BOOL)updateObjects:(NSArray *)array
{
for (DBModel *model in array) {
if (![model isKindOfClass:[DBModel class]]) {
return NO;
}
}
__block BOOL res = YES;
DBHelper *jkDB = [DBHelper shareInstance];
// 如果要支持事務
[jkDB.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
for (DBModel *model in array) {
NSString *tableName = NSStringFromClass(model.class);
id primaryValue = [model valueForKey:primaryId];
if (!primaryValue || primaryValue <= 0) {
res = NO;
*rollback = YES;
return;
}
NSMutableString *keyString = [NSMutableString string];
NSMutableArray *updateValues = [NSMutableArray array];
for (int i = 0; i < model.columeNames.count; i++) {
NSString *proname = [model.columeNames objectAtIndex:i];
if ([proname isEqualToString:primaryId]) {
continue;
}
[keyString appendFormat:@" %@=?,", proname];
id value = [model valueForKey:proname];
if (!value) {
value = @"";
}
[updateValues addObject:value];
}
//刪除最後那個逗號
[keyString deleteCharactersInRange:NSMakeRange(keyString.length - 1, 1)];
NSString *sql = [NSString stringWithFormat:@"UPDATE %@ SET %@ WHERE %@=?;", tableName, keyString, primaryId];
[updateValues addObject:primaryValue];
BOOL flag = [db executeUpdate:sql withArgumentsInArray:updateValues];
NSLog(flag?@"更新成功":@"更新失敗");
if (!flag) {
res = NO;
*rollback = YES;
return;
}
}
}];
return res;
}
/** 刪除單個對象 */
- (BOOL)deleteObject
{
DBHelper *jkDB = [DBHelper shareInstance];
__block BOOL res = NO;
[jkDB.dbQueue inDatabase:^(FMDatabase *db) {
NSString *tableName = NSStringFromClass(self.class);
id primaryValue = [self valueForKey:primaryId];
if (!primaryValue || primaryValue <= 0) {
return ;
}
NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@ = ?",tableName,primaryId];
res = [db executeUpdate:sql withArgumentsInArray:@[primaryValue]];
NSLog(res?@"刪除成功":@"刪除失敗");
}];
return res;
}
/** 批量刪除用戶對象 */
+ (BOOL)deleteObjects:(NSArray *)array
{
for (DBModel *model in array) {
if (![model isKindOfClass:[DBModel class]]) {
return NO;
}
}
__block BOOL res = YES;
DBHelper *jkDB = [DBHelper shareInstance];
// 如果要支持事務
[jkDB.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
for (DBModel *model in array) {
NSString *tableName = NSStringFromClass(model.class);
id primaryValue = [model valueForKey:primaryId];
if (!primaryValue || primaryValue <= 0) {
return ;
}
NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@ = ?",tableName,primaryId];
BOOL flag = [db executeUpdate:sql withArgumentsInArray:@[primaryValue]];
NSLog(flag?@"刪除成功":@"刪除失敗");
if (!flag) {
res = NO;
*rollback = YES;
return;
}
}
}];
return res;
}
/** 通過條件刪除數據 */
+ (BOOL)deleteObjectsByCriteria:(NSString *)criteria
{
DBHelper *jkDB = [DBHelper shareInstance];
__block BOOL res = NO;
[jkDB.dbQueue inDatabase:^(FMDatabase *db) {
NSString *tableName = NSStringFromClass(self.class);
NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ %@ ",tableName,criteria];
res = [db executeUpdate:sql];
NSLog(res?@"刪除成功":@"刪除失敗");
}];
return res;
}
/** 通過條件刪除 (多參數)--2 */
+ (BOOL)deleteObjectsWithFormat:(NSString *)format, ...
{
va_list ap;
va_start(ap, format);
NSString *criteria = [[NSString alloc] initWithFormat:format locale:[NSLocale currentLocale] arguments:ap];
va_end(ap);
return [self deleteObjectsByCriteria:criteria];
}
/** 清空表 */
+ (BOOL)clearTable
{
DBHelper *jkDB = [DBHelper shareInstance];
__block BOOL res = NO;
[jkDB.dbQueue inDatabase:^(FMDatabase *db) {
NSString *tableName = NSStringFromClass(self.class);
NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@",tableName];
res = [db executeUpdate:sql];
NSLog(res?@"清空成功":@"清空失敗");
}];
return res;
}
///0708DB
/** 查詢全部數據 */
+ (NSArray *)findAll
{
NSLog(@"jkdb---%s",__func__);
DBHelper *jkDB = [DBHelper shareInstance];
NSMutableArray *users = [NSMutableArray array];
[jkDB.dbQueue inDatabase:^(FMDatabase *db) {
NSString *tableName = NSStringFromClass(self.class);
NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@",tableName];
FMResultSet *resultSet = [db executeQuery:sql];
while ([resultSet next]) {
DBModel *model = [[self.class alloc] init];
for (int i=0; i< model.columeNames.count; i++) {
NSString *columeName = [model.columeNames objectAtIndex:i];
NSString *columeType = [model.columeTypes objectAtIndex:i];
if ([columeType isEqualToString:SQLTEXT]) {
[model setValue:[resultSet stringForColumn:columeName] forKey:columeName];
} else {
[model setValue:[NSNumber numberWithLongLong:[resultSet longLongIntForColumn:columeName]] forKey:columeName];
}
}
[users addObject:model];
FMDBRelease(model);
}
}];
return users;
}
+ (instancetype)findFirstWithFormat:(NSString *)format, ...
{
va_list ap;
va_start(ap, format);
NSString *criteria = [[NSString alloc] initWithFormat:format locale:[NSLocale currentLocale] arguments:ap];
va_end(ap);
return [self findFirstByCriteria:criteria];
}
/** 查找某條數據 */
+ (instancetype)findFirstByCriteria:(NSString *)criteria
{
NSArray *results = [self.class findByCriteria:criteria];
if (results.count < 1) {
return nil;
}
return [results firstObject];
}
+ (instancetype)findByPK:(int)inPk
{
NSString *condition = [NSString stringWithFormat:@"WHERE %@=%d",primaryId,inPk];
return [self findFirstByCriteria:condition];
}
+ (NSArray *)findWithFormat:(NSString *)format, ...
{
va_list ap;
va_start(ap, format);
NSString *criteria = [[NSString alloc] initWithFormat:format locale:[NSLocale currentLocale] arguments:ap];
va_end(ap);
return [self findByCriteria:criteria];
}
/** 通過條件查找數據 */
+ (NSArray *)findByCriteria:(NSString *)criteria
{
DBHelper *jkDB = [DBHelper shareInstance];
NSMutableArray *users = [NSMutableArray array];
[jkDB.dbQueue inDatabase:^(FMDatabase *db) {
NSString *tableName = NSStringFromClass(self.class);
NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ %@",tableName,criteria];
FMResultSet *resultSet = [db executeQuery:sql];
while ([resultSet next]) {
DBModel *model = [[self.class alloc] init];
for (int i=0; i< model.columeNames.count; i++) {
NSString *columeName = [model.columeNames objectAtIndex:i];
NSString *columeType = [model.columeTypes objectAtIndex:i];
if ([columeType isEqualToString:SQLTEXT]) {
[model setValue:[resultSet stringForColumn:columeName] forKey:columeName];
} else {
[model setValue:[NSNumber numberWithLongLong:[resultSet longLongIntForColumn:columeName]] forKey:columeName];
}
}
[users addObject:model];
FMDBRelease(model);
}
}];
return users;
}
#pragma mark - util method
+ (NSString *)getColumeAndTypeString
{
NSMutableString* pars = [NSMutableString string];
NSDictionary *dict = [self.class getAllProperties];
NSMutableArray *proNames = [dict objectForKey:@"name"];
NSMutableArray *proTypes = [dict objectForKey:@"type"];
for (int i=0; i< proNames.count; i++) {
[pars appendFormat:@"%@ %@",[proNames objectAtIndex:i],[proTypes objectAtIndex:i]];
if(i+1 != proNames.count)
{
[pars appendString:@","];
}
}
return pars;
}
- (NSString *)description
{
NSString *result = @"";
NSDictionary *dict = [self.class getAllProperties];
NSMutableArray *proNames = [dict objectForKey:@"name"];
for (int i = 0; i < proNames.count; i++) {
NSString *proName = [proNames objectAtIndex:i];
id proValue = [self valueForKey:proName];
result = [result stringByAppendingFormat:@"%@:%@\n",proName,proValue];
}
return result;
}
#pragma mark - must be override method
/** 如果子類中有一些property不需要創建數據庫字段,那麽這個方法必須在子類中重寫
*/
+ (NSArray *)transients
{
return [NSArray array];
}
@end
ios常用數據庫