首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQLDelight:如何动态创建表?

SQLDelight:如何动态创建表?
EN

Stack Overflow用户
提问于 2021-03-25 11:48:12
回答 1查看 465关注 0票数 1

我看到了一些例子,在这些例子中,我们可以使用这样的sq文件创建一个具有固定名称的表

代码语言:javascript
复制
CREATE TABLE hockeyPlayer (
  player_number INTEGER NOT NULL,
  full_name TEXT NOT NULL
);

我需要在运行时创建任意名称的表,如何实现这一点?

UPD

在本例中,我似乎必须手动执行所有查询(就像在生成的类中那样)

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-26 12:30:38

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

代码语言:javascript
复制
    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")
        }

    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66798870

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档