//
// CCSqlite3.h
// CCFC
//
//
#import <Foundation/Foundation.h>
#import <sqlite3.h>
@class CCSqlite3;
@protocol CCSqlite3Delegate
// the row starts with 1.
- (void)onCCSqlite3AnotherRowOK:(CCSqlite3 *)sqlite withRow:(int)row;
@end
@interface CCSqlite3 : NSObject
{
@private
sqlite3 *_db;
NSString *_sql;
sqlite3_stmt *_statement;
id<CCSqlite3Delegate> _delegate;
int _row;
}
@property(nonatomic, assign) id delegate;
// if you don't want to call getData method, then get the statement by yourself.
@property(nonatomic, assign, readonly) sqlite3_stmt *statement;
- (id)initWithSqliteDBFullPath:(NSString *)dbFullPath;
- (void)dealloc;
- (void)setSql:(NSString *)sql;
- (BOOL)prepare;
- (void)getData;
- (void)end;
// set so, we can get the random results
- (void)setRandomReturns:(int)n;
// if set so, the sqlite will returns the rowCount row data, which starts from argument start.
- (void)setNRowsFrom:(int)start withRowCount:(int)rowCount;
@end
//
// CCSqlite3.m
// CCFC
//
//
#import "CCSqlite3.h"
@implementation CCSqlite3
@synthesize delegate = _delegate;
@synthesize statement = _statement;
- (id)initWithSqliteDBFullPath:(NSString *)dbFullPath
{
self = [super init];
int ret;
if(self)
{
ret = sqlite3_open([dbFullPath UTF8String], &_db);
if(ret != SQLITE_OK)
return nil;
}
return self;
}
- (void)dealloc
{
[_sql release];
sqlite3_close(_db);
[super dealloc];
}
- (void)setSql:(NSString *)sql
{
if(_sql != sql)
{
[_sql release];
_sql = [sql copy];
}
}
- (BOOL)prepare
{
return (sqlite3_prepare_v2(_db, [_sql UTF8String], -1, &_statement, NULL) == SQLITE_OK);
}
- (void)getData
{
while (sqlite3_step(_statement) == SQLITE_ROW)
{
++_row;
[_delegate onCCSqlite3AnotherRowOK:self withRow:_row];
}
}
- (void)end
{
sqlite3_finalize(_statement);
}
// set so, we can get the random results
- (void)setRandomReturns:(int)n
{
NSString *temp = [NSString stringWithFormat:@" order by random() limit %d", n];
NSString *final = [_sql stringByAppendingString:temp];
[self setSql:final];
}
// if set so, the sqlite will returns the rowCount row data, which starts from argument start.
- (void)setNRowsFrom:(int)start withRowCount:(int)rowCount
{
NSString *temp = [NSString stringWithFormat:@" limit %d,%d", start, rowCount];
NSString *final = [_sql stringByAppendingString:temp];
[self setSql:final];
}
@end
微风不燥,阳光正好,你就像风一样经过这里,愿你停留的片刻温暖舒心。
我是程序员小迷(致力于C、C++、Java、Kotlin、Android、Shell、JavaScript、TypeScript、Python等编程技术的技巧经验分享),若作品对您有帮助,请关注、分享、点赞、收藏、在看、喜欢,您的支持是我们为您提供帮助的最大动力。
欢迎关注。助您在编程路上越走越好!