I would like to print my sql table contents and for that reason, I would like to retrieve the column name from the table. One solution I came across was :
SELECT sql FROM sqlite_master WHERE tbl_name = 'table_name' AND type = 'table'
But looks like I will have to parse the results.
Another suggestion was to use:
PRAGMA table_info(table_name);
but the below sqlite page suggests not to use this : http://www.sqlite.org/pragma.html#pragma_full_column_names
Does there exists any way to achieve this. Also what would be the syntax to use
PRAGMA table_info(table_name);
Above solutions have been taken from here
The SQLite command line shell also allows you to use “line” mode. When you do this, the query results are displayed vertically, so that each column is listed on a new line. When you use this mode, the column names are also displayed, using the format column_name = value.
By default, the SQLite command line interface displays query results using a pipe-separated list, without column headers. This might be fine if you’re using the results in an application that doesn’t need the column names, but if you’re just a human, it can make it hard to read the data, especially if there are lots of columns.
You're going to want to use an sqlite pragma statement. A pragma statement lets you query database meta-data or in some cases alter the behavior of the database. The pragma that gives you column headers is called "table_info."
To get a list of column names from a table in a SQLite database or getting the row or rows back as a dictionary solution is just one extra line of code when setting the connection. So yes, there is a simple way of getting the column names. The solution is in one single line! conn.row_factory = sqlite3.Row is as easy as this!
Since your question is tagged c
I assume you have access to the SQLite C API. If you create a prepared statement with one of the prepare_v2 functions that selects from the table you want you can use sqlite3_column_name to get the name of each column.
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