ios - 如何使用 SQLite 数据库在 Swift 中创建多个表?
问题描述
所以我能够做一个教程来创建一个表,但是当我尝试创建另一个表时,它没有出现在 SQLite 的 DB 浏览器中,这让我认为它没有被创建。
有没有办法在同一个数据库管理类中创建多个表?
// Creating DB connection
db = try Connection("/blahblahblah/harmonyMoodDB.sqlite3")
// Creating table object
meds = Table("medications")
// Create instances of each column
medID = Expression<Int64>("id")
name = Expression<String>("name")
dosage = Expression<Int64>("dosage")
if (!UserDefaults.standard.bool(forKey: "is_db_created")) {
// If not, then create the table
try db.run(meds.create { (t) in
t.column(medID, primaryKey: true)
t.column(name)
t.column(dosage)
})
// Set the value to true, so it will not attempt to create the table again
UserDefaults.standard.set(true, forKey: "is_db_created")
}
// Creating table object
users = Table("users")
// Create instances of each column
userID = Expression<Int64>("userID")
userName = Expression<String>("userName")
if (!UserDefaults.standard.bool(forKey: "is_db_created")) {
// If not, then create the table
try db.run(users.create { (t) in
t.column(userID, primaryKey: true)
t.column(userName)
})
// Set the value to true, so it will not attempt to create the table again
UserDefaults.standard.set(true, forKey: "is_db_created")
}
}
catch {
// Show error message (if any)
print(error.localizedDescription)
}
} // End of init
我在哪里错了?
解决方案
正如上面评论中提到的,问题在于存储is_db_created
在用户默认值中。就个人而言,无论如何我都不会在这种情况下使用用户默认值 - 如果您最终还是使用它,请确保您只存储它,如果您的完整初始化成功!(目前,如果您的语句失败,您仍然存储数据库已创建。
我的首选解决方案是
// Creating table object
meds = Table("medications")
// Create instances of each column
medID = Expression<Int64>("id")
name = Expression<String>("name")
dosage = Expression<Int64>("dosage")
// CREATE TABLE "meds" IF NOT EXISTS -- ...
try db.run(meds.create(ifNotExists: true) { t in /* ... */ })
// same for users
/* ... */
这还有一个优点,即您的代码对于“外部”创建的表或数据库模式等具有强大的功能。有关更多详细信息,另请参阅doc
推荐阅读
- javascript - 在select2下拉列表中动态设置maximumSelectionLength?
- python-3.x - 通过填充孔合并列表
- java - 在 gradle 同步时面临问题 - 找不到 lint-gradle-api.jar (com.android.tools.lint:lint-gradle-api:26.1.2)
- flutter - Flutter MapView 实例问题。第二次看不到标记
- asp.net - 启用 Postman 客户端缓存
- angular - 有没有办法从 Angular 6 Universal 的 server.ts 文件中的 interceptor.service.ts 访问变量?
- angular - 角度无法识别“napa”
- mysql - 如何使用 if check 更改多个表的列数据类型?
- scala - 结合scala宏注解
- java - 将 .txt Spark 输出转换为 .csv