7

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

1

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What if you don't have any records in that table?
I believe the column names are still available even if there are no results.
4

You can safely use PRAGMA table_info(table-name); since it's not deprecated in any way (yours post links to another pragma).

Comments

1
int sqlite3_get_table( sqlite3 *db, /* An open database */ const char *zSql, /* SQL to be evaluated */ char ***pazResult, /* Results of the query */ int *pnRow, /* Number of result rows written here */ int *pnColumn, /* Number of result columns written here */ char **pzErrmsg /* Error msg written here */ ); 

If you are using c/c++, you can use the function sqlite3_get_table(db, query, result, nrow, ncol, errmsg);

Make the query as select * from table;

And the first few results result[0], result[1]...... will have the column names.

1 Comment

That function is deprecated: "This is a legacy interface that is preserved for backwards compatibility. Use of this interface is not recommended."
0

This setting will toggle showing column names as part of the return for select statements:

.headers on 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.