【问题标题】:SQLDelight: how to create table dynamically?SQLDelight:如何动态创建表?
【发布时间】:2021-06-22 05:10:45
【问题描述】:

我看到了我们可以使用 sq 这样的文件创建具有固定名称的表的示例

CREATE TABLE hockeyPlayer (
  player_number INTEGER NOT NULL,
  full_name TEXT NOT NULL
);

我需要在运行时创建具有任意名称的表,我该如何实现?

UPD

在这种情况下,我似乎必须手动执行所有查询(就像在生成的类中完成的那样)

val driver = DatabaseDriverFactory().createDriver(databaseName)
val tableName = "table2"
driver.execute(null, "CREATE TABLE IF NOT EXISTS $tableName (player_number INTEGER NOT NULL, full_name TEXT NOT NULL", 0, null)

【问题讨论】:

    标签: kotlin-multiplatform sqldelight


    【解决方案1】:

    这是手动/动态表创建和操作的示例

        fun test(databaseName: String, key: String?) {
            val driver = DatabaseDriverFactory().createDriver(databaseName, key)
            val tableName = "table2"
            val identifier = 1
    
            // identifier here must be null to avoid SQLiteBindOrColumnIndexOutOfRangeException
            // in INSERT statements below
            driver.execute(null, "CREATE TABLE IF NOT EXISTS $tableName (player_number INTEGER NOT NULL, full_name TEXT NOT NULL)", 0, null)
            var cursor = driver.executeQuery(identifier, "SELECT * FROM $tableName", 0, null)
    
            if (!cursor.next()) {
                Napier.i("EMPTY TEST DB")
                driver.execute(identifier, "INSERT INTO $tableName (player_number, full_name) VALUES (?, ?)", 2) {
                    // indices start here from 1
                    bindLong(1, 1)
                    bindString(2, "John")
                }
                driver.execute(identifier, "INSERT INTO $tableName (player_number, full_name) VALUES (?, ?)", 2) {
                    bindLong(1, 2)
                    bindString(2, "Mike")
                }
            }
    
            cursor = driver.executeQuery(identifier, "SELECT * FROM $tableName", 0, null)
    
            while (cursor.next()) {
                // indices start here from 0
                val number = cursor.getLong(0)
                val name = cursor.getString(1)
                Napier.i("Player #$number $name")
            }
    
        }
    

    【讨论】:

      猜你喜欢
      • 2011-07-18
      • 2013-11-18
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 2019-12-16
      • 2011-01-26
      • 2019-03-20
      • 2019-08-15
      相关资源
      最近更新 更多