我正在尝试创建一种通用方法来删除项目中所有数据库文件中的所有行。 我不想存储和传递所有表名称,因此它应该仅适用于数据库文件路径。 我尝试通过以下代码从数据库文件中获取所有表:
guard
let path = getDBPath(for: .contacts),
let dbQueue = FMDatabaseQueue(path: path)
else { return }
dbQueue.inDatabase { fmdb in
do {
let resultSet = try fmdb.executeQuery(
"SELECT name FROM sqlite_master WHERE type='table'",
values: nil
)
// what is next?
} catch {
// log error
}
}
但是我不知道
fmdb.executeQuery
之后我要做什么。
我需要打电话到哪里"DELETE FROM \(tableName)"
?
好吧,我终于成功了:
let resultSet = try fmdb.executeQuery(
"SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%object%'", // I use `AND name LIKE '%object%'` to not clear any internal (system) tables, all my own entities have `object` word in their names
values: []
)
while resultSet.next() {
if let table = resultSet.string(forColumn: "name") {
try fmdb.executeUpdate(
"DELETE FROM \(table)",
values: []
)
}
}