5

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).

asked Apr 22, 2016 at 4:03

1 Answer 1

11

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)
}
answered Apr 22, 2016 at 4:03
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.