SQLite
RTDB 是建立在 SQLite 之上的。
了解更多
SQLite 主页
SQLite 文档
安装
CocoaPods 安装
platform :ios, '8.2'
pod 'RTDatabase'
通过克隆仓库安装
如何使用
- RTDB
RTDB 需要 ARC。
默认情况下使用标志打开 sqlite3
SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_SHAREDCACHE
或者您也可以自定义标志。
- 打开
在使用RTDB之前,它必须被打开。
// init a RTDB instance.
RTDB *db = [[RTDB alloc] init];
// Open DB
NSError *err;
BOOL result = [db openWithPath:@"~/RTDB.sqlite3" withError:&err];
if (!result) {
NSLog(@"%@". err);
}
- 执行
如果sql字符串没有SELECT
,您可以调用以execQuery
开头的等效方法,这些方法返回的数据类型为BOOL。
这些方法实际上是sqlite3_prepare_v2()
、sqlite3_step()
和sqlite3_finalize()
的包装。
// creat table
[db execQuery:@"CREATE TABLE if not exists 'DB' \
('name' 'TEXT', 'data' 'BLOB', 'n' 'REAL', 'date' 'REAL', \
'f' 'REAL', 'd' 'REAL', 'c' 'INTEGER', 'uc' 'INTEGER')", nil];
// insert
/**
* sql like
* @"INSERT INTO DB (name, data, n, date, f, d, c, uc) \
* VALUES (:name, :data, :n, :date, :f, :d, :c, :uc)"
* is supported better.
*/
[db execQuery:
@"INSERT INTO DB (name, data, n, date, f, d, c, uc) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
@"_name",
[@"test" dataUsingEncoding:NSUTF8StringEncoding],
[NSDate date],
[NSNumber numberWithDouble:123.213124324],
@(1.2),
@(1.2123124),
@(-'c'),
@('c'),
nil];
以execSql
开头的以太网方法返回一个RTNext对象。如果sql字符串包含一个'SELECT',调用这些方法。
RTNext对象类型可以调用step
来查看是否存在下一级。或者使用enumAllSteps
、enumAllColumns
来枚举每个步骤的值。
// select
RTNext *next = [db execSql:@"SELECT * FROM DB", nil];
[next enumAllSteps:^(NSDictionary *dic, int step, BOOL *stop, NSError *err) {
if (!err) {
NSLog(@"%@", dic);
} else {
// err handle.
}
}];
BOOL step = [next step]; // When sqlite3_step() == SQLITE_ROW, return YES.
- RTDB默认
RTDB默认继承自RTDB,因此在使用RTDB默认时,启用了所有RTDB的方法。
RTDB默认可以自动通过类创建一个表,并将从表中选出的每一行转换为具有相同表名称的对象类型。需要注意的是,该类必须有一个名为"_id"的属性,其类型为整数。_id
设置为默认主键;
// init a RTDBDefault instance.
RTDBDefault *defaultDB = [[RTDBDefault alloc] init];
// creat table for model class.
NSError *err;
[defaultDB creatTable:[DB class] withError:&err];
/**
* @interface DB : NSObject
* // _id is needed for primary key
* @property (nonatomic, assign) NSInteger _id;
* @end
*/
DB *obj = [[DB alloc] init];
// insert
[defaultDB insertObj:obj withError:&err];
// update
[defaultDB updateObj:obj withError:&err];
// delete
[defaultDB deleteObj:obj withError:&err];
NSArray <DB *>*arr = [defaultDB
fetchObjSql:@"SELECT * FROM DB order by _id" withError:&err];
NSArray <NSDictionary *>*arr = [defaultDB
fetchSql:@"SELECT * FROM DB order by _id" withError:&err];
- RTSDB & RTSDBExtra
RTSDB & RTSDBExtra提供一种链式使用RTDB & RTDBDefault的方法。
当调用RTSDB实例的方法时,它将返回一个新的RTSDBExtra实例。RTSDBExtra的实例方法是可以链接的。您可以使用点符号来调用每个方法。
// init a RTSDB instance.
RTSDB *db = [[RTSDB alloc] init];
db.onDefault
.onOpen(@"~/RTDB.sqlite3")
.onError(^(NSError *err) {
NSLog(@"%@", err);
});
在RTSDBExtra中,提供了一个异步执行方案。当调用onMain
时,该操作将在主队列上执行。调用onQueue
后,该操作将在指定的队列上执行。
如果设置了默认队列,则在调用onDefault
后,下一次操作将在默认队列上执行。否则,它将在主队列上执行。在调用的过程中,队列可以多次切换。
onQueue
不会更改默认队列。
// select
db.onDefault
.execArgs(@"SELECT * FROM DB", nil) 0))
.onQueue(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0))
.onEnum(^(NSDictionary *dic, int step, BOOL *stop){
// Called in a subqueue
NSLog(@"%@", dic);
NSLog(@"%d", step);
NSLog(@"%@", [NSThread currentThread]);
})
.onError(^(NSError *err) {
NSLog(@"%@", err);
});
- 准备SQL
RTDB提供了一种快速构建SQL字符串的解决方案。具体实现在以PP开始的类中。
所有以PP开始的类都遵循PPSQLProtocol协议。该协议有两个方法(build、add)和一个必须的属性(mStrResult),以及一些可选方法。
必须的属性名为mStrResult,是SQL字符串的容器。
PPSQL为创建SQLite常见操作的SQL提供了几个入口方法。
- 如果需要在SQL字符串中添加列,请在调用相应的入口方法后调用
subs
方法。subs
方法将回调遵循PPSQLProtocol协议的对象。请详细查看PPSubSQL.h
文件。
e.g.
/**
* To create tables,
* you need to tell SQLite all columns and every column's database type.
*/
PPSQL *pp = [[PPSQL alloc] init];
NSString *sql = pp.CREATE(@"Person").subs(^(id<PPSQLProtocol> sub) {
sub.INTEGER(@"_id").primaryKey.autoincrement.notNull
.TEXT(@"name")
.INTEGER(@"age")
.REAL(@"height")
.BLOB(@"info");
}).build;
NSLog(@"%@", sql);
Print Result:
-> CREATE TABLE if not exists 'Person'
('_id' 'INTEGER' primary key autoincrement NOT NULL,
'name' 'TEXT', 'age' 'INTEGER', 'height' 'REAL', 'info' 'BLOB')
- 如果要在SQL字符串中添加限定条件,请调用
terms
方法。terms
方法将返回一个类型为PPTerm
的对象。PPTerm
包含许多SQLite SQL子句。请根据需要选择它们。
e.g.
sql = pp.UPDATE(@"Person").subs(^(id<PPSQLProtocol> sub) {
sub.column(@"age");
}).terms(^(PPTerm *term) {
term.where.equal(@"_id", @(1));
}).build;
NSLog(@"%@", sql);
Print Result:
-> UPDATE Person SET age = ? WHERE _id = 1
- 自定义SQL字符串,请尝试调用方法
添加
。
请注意
无限定参数需要以 nil 结尾。
作者
中文参考
许可证
所有源代码均受 MIT 许可证的许可。