Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For debugging purposes I am trying to get a simple list of the column names in my SQLite table. I am using the SQLite.swift framework.

My question is more specific than How to get a list of column names on sqlite3 / iPhone? so I am creating a new question.

Using

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

by applying this answer to the documentation didn't work for me (nothing happened).

like image 765
Suragch Avatar asked Apr 22 '16 04:04

Suragch


1 Answers

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)
}
like image 106
Suragch Avatar answered Sep 18 '22 02:09

Suragch