【发布时间】:2021-06-02 14:51:26
【问题描述】:
所以我可以编写一个教程来创建一个表,但是当我尝试创建另一个表时,它没有显示在 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 设置为 true。所以,代码不会被执行。
-
啊,所以我需要将其设置为 false,然后将我在第二个表之后所做的第二个语句设置为 true?
-
if on is_db_create 应该在创建第一个表之前开始,并在创建第二个表之后结束。然后 is_db_create 创建并仅在创建第二个表时设置为 true。
-
您能评论一下代码的外观吗?我仍然很难弄清楚。
标签: ios swift database sqlite sqlite.swift