How to get a list of column names on Sqlite3 datab

2020-01-25 03:25发布

I want to migrate my iPhone app to a new database version. Since I don't have some version saved, I need to check if certain column names exist.

This Stackoverflow entry suggests doing the select

SELECT sql FROM sqlite_master
WHERE tbl_name = 'table_name' AND type = 'table'

and parse the result.

Is that the common way? Alternatives?

标签: iphone sqlite
17条回答
时光不老,我们不散
2楼-- · 2020-01-25 03:54

If you have the sqlite database, use the sqlite3 command line program and these commands:

To list all the tables in the database:

.tables

To show the schema for a given tablename:

.schema tablename
查看更多
Lonely孤独者°
3楼-- · 2020-01-25 03:55
PRAGMA table_info(table_name);

will get you a list of all the column names.

查看更多
叛逆
4楼-- · 2020-01-25 03:56

If you want the output of your queries to include columns names and be correctly aligned as columns, use these commands in sqlite3:

.headers on
.mode column

You will get output like:

sqlite> .headers on
sqlite> .mode column
sqlite> select * from mytable;
id          foo         bar
----------  ----------  ----------
1           val1        val2
2           val3        val4
查看更多
神经病院院长
5楼-- · 2020-01-25 03:56

When you run the sqlite3 cli, typing in:

sqlite3 -header

will also give the desired result

查看更多
家丑人穷心不美
6楼-- · 2020-01-25 03:57

Maybe you just want to print the table headers on the console. This is my code: (for each table)

    // ------------------ show header ----------------


    char sqlite_stmt_showHeader[1000];
    snprintf(sqlite_stmt_showHeader, 1000, "%s%s", "SELECT * FROM ", TABLE_NAME_STRING UTF8String]);

    sqlite3_stmt* statement_showHeader;
    sqlite3_prepare_v2(DATABASE, sqlite_stmt_showHeader, -1, &statement_showHeader, NULL);

    int headerColumnSize = sqlite3_column_count(statement_showHeader);

    NSString* headerRow = @"|";

    for (int j = 0; j < headerColumnSize; j++) {
        NSString* headerColumnContent = [[NSString alloc] initWithUTF8String:(const char*)sqlite3_column_name(statement_showHeader, j)];
        headerRow = [[NSString alloc] initWithFormat:@"%@ %@ |", headerRow, headerColumnContent];
    }

    NSLog(@"%@", headerRow);


    sqlite3_finalize(statement_showHeader);

    // ---------------- show header end ---------------------
查看更多
登录 后发表回答