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

asked Aug 24, 2011 at 1:07
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.

answered Aug 24, 2011 at 1:14
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).

BenMorel
36.9k52 gold badges208 silver badges339 bronze badges
answered Aug 24, 2011 at 3:34

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.

answered Aug 24, 2011 at 1:48

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
answered Jan 7, 2019 at 1:51

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.