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).
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With