首页 > 解决方案 > 如何使用 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

我在哪里错了?

标签: iosswiftdatabasesqlitesqlite.swift

解决方案


正如上面评论中提到的,问题在于存储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


推荐阅读