Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get column names in sqlite3

Tags:

c++

c

sqlite

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

like image 868
keeda Avatar asked Aug 24 '11 01:08

keeda


People also ask

How do I display column names in SQLite?

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.

How do you display query results in SQLite?

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.

How do I get the column headers in SQLite?

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

How to get a list of column names from a table?

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!


1 Answers

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.

like image 87
Wes Avatar answered Oct 05 '22 16:10

Wes