注:本文OC和Swift代码混编。主要是熟悉用法。中心思想都是一样的。
FMDB对libsqlite3进行了封装,API更加友好,使用非常方便。
三个重要类FMDatabase
、FMResultSet
、FMDatabaseQueue
-
FMDatabase
代表一个SQLite
数据库,用于执行SQL语句 -
FMDatabaseQueue
代表执行查询完成的结果集 -
FMDatabaseQueue
多线程中查询和更新数据库,线程安全
创建数据库
路径中文件不存在,则自动创建一个;有则直接返回数据库。
FMDatabase *database = [FMDatabase databaseWithPath:self.getDBPath]; //给一个路径即可
打开数据库
- SQLITE_OPEN_NOMUTEX标识创建多线程模式的连接
- 操作数据库之前确定数据库能被打开
OC
if (![db open]) {
// [db release]; // uncomment this line in manual referencing code; in ARC, this is not necessary/permitted
db = nil;
return;
}
Swift
guard database.open(withFlags: SQLITE_OPEN_READWRITE|SQLITE_OPEN_NOMUTEX) else {
return
}
获取FMDatabaseQueue
FMDatabaseQueue *readOnlyDBQueue = [FMDatabaseQueue databaseQueueWithPath:self.getDBPath flags:SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX]
数据库自定义函数
如自定义一个两个定位点之间的距离函数
[db makeFunctionNamed:@"distance"
maximumArguments:4
withBlock:^(void *context, int argc, void **argv) {
// check that we have four arguments (lat1, lon1, lat2, lon2)
assert(argc == 4);
// check that all four arguments are non-null
if (sqlite3_value_type(argv[0]) == SQLITE_NULL || sqlite3_value_type(argv[1]) == SQLITE_NULL || sqlite3_value_type(argv[2]) == SQLITE_NULL || sqlite3_value_type(argv[3]) == SQLITE_NULL) {
sqlite3_result_null(context);
return;
}
// get the four argument values
double lat1 = sqlite3_value_double(argv[0]); //纬度
double lon1 = sqlite3_value_double(argv[1]); //经度
double lat2 = sqlite3_value_double(argv[2]);//currentLocatin 纬度
double lon2 = sqlite3_value_double(argv[3]);//currentLocatin经度
// convert lat1 and lat2 into radians now, to avoid doing it twice below
double lat1rad = DEG2RAD(lat1);
double lat2rad = DEG2RAD(lat2);
// apply the spherical law of cosines to our latitudes and longitudes, and set the result appropriately
// 6378.1 is the approximate radius of the earth in kilometres
sqlite3_result_double(context, acos(sin(lat1rad) * sin(lat2rad) + cos(lat1rad) * cos(lat2rad) * cos(DEG2RAD(lon2) - DEG2RAD(lon1))) * 6378.1);
}];
数据库查询
FMDatabaseQueue 查询。
- 用
while
遍历所有结果集
while ([resultSet next]) {
//retrieve values for each record
}
- 只要要获取查询的结果,则必须调用
[resultSet next]
,不管是否是取一条数据还是遍历完所有的数据 -
close
方法一般情况下不需要自己调用(特别是while
循环遍历完所有的结果集时)
Typically, there's no need to
-close
anFMResultSet
yourself, since that happens when either the result set is exhausted. However, if you only pull out a single request or any other number of requests which don't exhaust the result set, you will need to call the-close
method on theFMResultSet
.
- 查询距离定位点在radius以内的所有数据
[self.readOnlyDBQueue inDatabase:^(FMDatabase *db) {
NSNumber* radius = @"100";
NSString *sql = [NSString stringWithFormat:@"SELECT %@, distance(latitude, longitude, %f, %f) as dist FROM places WHERE dist < %f order by dist",
[Place shortQuery],
latitude.doubleValue,
longitude.doubleValue,
radius.doubleValue*1.6
];
FMResultSet *resultSet = [db executeQuery:sql]; //查询语句
while (resultSet && [resultSet next]) {
Place *place = [Place placeWithShortResultSet:resultSet];
if (place) {
[result addObject: place];
}
}
}];
数据库更新
- 非
SELECT
操作,其他的操作都视为更新。更新操作会返回一个Bool值表示操作是否成功。失败可以打印错误描述 - 拼接更新参数。如:
OC
BOOL success = [db executeUpdate:@"INSERT INTO authors (identifier, name, date, comment) VALUES (?, ?, ?, ?)", @(identifier), name, date, comment ?: [NSNull null]];
Swift
withArgumentsIn
中传入?的值(一个数组)
//1.
let sql = "UPDATE places SET rating = ? WHERE ident = ?"
database.executeUpdate(sql, withArgumentsIn: [rating.rating, rating.id])
//2. 很多参数
//数据库中的几种类型
/*
private protocol DBAvailableType {}
extension Bool: DBAvailableType {}
extension String: DBAvailableType {}
extension Int: DBAvailableType {}
extension Int16: DBAvailableType {}
extension Double: DBAvailableType {}
extension NSNull: DBAvailableType {}
*/
var arguments: [DBAvailableType] = [] //DBAvailableType是 `protocol`。小技巧:这样arguments就可以包含多种类型的值,如Bool, String......
var keys = ""
var values = ""
func addValue(key: String, object: Any?) {
guard !key.isEmpty else {
return
}
if let obj = object as? DBAvailableType {
keys.append("\(key),")
values.append("?,")
arguments.append(obj)
} else if let _ = object {
return
} else {
keys.append("\(key),")
values.append("?,")
arguments.append(NSNull())
}
}
// 像这样添加参数和值
addValue(key: "place_id", object: placeExtension.placeID)
// remove last symbol - , 处理多余的,
if let last = keys.last, last == "," {
keys.removeLast()
}
if let last = values.last, last == "," {
values.removeLast()
}
let replaceSql = "REPLACE INTO place_extension (\(keys)) VALUES (\(values))"
// executeUpdate是需要 do catch处理的。这里省略了。
database.executeUpdate(replaceSql, values: arguments)
- 更新评分例子
let database = FMDatabase(path: self.dbPath)
guard database.open(withFlags: SQLITE_OPEN_READWRITE|SQLITE_OPEN_NOMUTEX) else {
return
}
database.beginTransaction()
for rating in ratings {
let sql = "UPDATE places SET rating = ? WHERE ident = ?"
if database.executeUpdate(sql, withArgumentsIn: [rating.rating, rating.id]) == false {
print("can't update")
print(database.lastError().localizedDescription)
}
}
database.commit()
database.close()
事务
- 可begin and commit一个事务(如上面的更新评分例子)
- 或者执行事务语句。如官方例子:
[queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", @1];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", @2];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", @3];
if (whoopsSomethingWrongHappened) {
*rollback = YES;
return;
}
}];
- 事务更新速度快。更新出错时事务可回滚。
关闭数据库
数据库使用完毕后记得要关闭
database.close()