如何获取带有 Sqlite.swift 的列名列表?

How to get a list of column names with Sqlite.swift?

出于调试目的,我试图在我的 SQLite table 中获取列名的简单列表。我正在使用 SQLite.swift framework.

我的问题比 How to get a list of column names on sqlite3 / iPhone? 更具体,所以我创建了一个新问题。

使用

try db.execute("PRAGMA table_info(table_name);")

通过应用 this answer to the documentation 对我不起作用(什么也没发生)。

假设您已经建立了一个名为 db 的数据库连接,要获取列名列表,您可以使用以下代码:

do {

    let tableInfo = Array(try db.prepare("PRAGMA table_info(table_name)"))
    for line in tableInfo {
        print(line[1]!, terminator: " ")
    }
    print()

} catch _ { }

其中 table_name 替换为您的 table 姓名的字符串。

您还可以添加

print(tableInfo)

查看有关您的 table 的更多 pragma 信息。

学分

感谢 提供有关如何执行此操作的线索。

示例函数

来自 Joe Blow 的测试例程以节省一些输入:

func findColumns(_ tableName:String) {

    var asAnArray:[String] = []
    do {
        let s = try db!.prepare("PRAGMA table_info(" + tableName + ")" )
        for row in s { asAnArray.append(row[1]! as! String) }
    }
    catch { print("some woe in findColumns for \(tableName) \(error)") }

    let asAString = asAnArray.joined(separator: ",")

    print(asAnArray)
    print(asAString)
}