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

最后都变了- 提交于 2019-12-05 09:56:25
Suragch

Assuming you already have a database connection called db set up, to get a list of the column names, you can use the following code:

do {

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

} catch _ { }

where table_name is replaced with the literal string of your table's name.

You can also add

print(tableInfo)

to see more pragma info about your table.

Credits

Thanks to this answer for clues of how to do this.

Example Function

Tested routine from Joe Blow to save a little typing:

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)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!