【问题标题】:How do I create multiple tables in Swift using SQLite database?如何使用 SQLite 数据库在 Swift 中创建多个表?
【发布时间】: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


【解决方案1】:

如上面的 cmets 所述,问题在于将 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 2020-12-21
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多