从objective-c中的sqlite数据库中检索表名

时间:2013-03-27 10:44:35

标签: ios objective-c sqlite

如何在objective-c中检索sqlite3表名。例如,如果我创建了几个表,现在我想在终端中显示(显示)他们的名称,如.table。谢谢。

4 个答案:

答案 0 :(得分:2)

SELECT name FROM sqlite_master WHERE type='table'

答案 1 :(得分:2)

使用以下代码:

-(NSMutableArray *)fetchTableNames
{   
    sqlite3_stmt* statement;
    NSString *query = @"SELECT name FROM sqlite_master WHERE type=\'table\'";
    int retVal = sqlite3_prepare_v2(YOUR_DB_OBJ, 
                                    [query UTF8String],
                                    -1,
                                    &statement,
                                    NULL);

    NSMutableArray *selectedRecords = [NSMutableArray array];
    if ( retVal == SQLITE_OK )
    {
        while(sqlite3_step(statement) == SQLITE_ROW )
        {
            NSString *value = [NSString stringWithCString:(const char *)sqlite3_column_text(statement, 0)
                                                 encoding:NSUTF8StringEncoding];
            [selectedRecords addObject:value];
        }       
    }   

    sqlite3_clear_bindings(statement);
    sqlite3_finalize(statement);

    return selectedRecords;
}

答案 2 :(得分:1)

SELECT * FROM sqlite_master where type='table'

试试这个。

答案 3 :(得分:0)

- (NSArray *)listOfColumnNamesForTable:(NSString *)tableName WithDBFilePath:(NSString*)databasePath {

sqlite3 *sqlite3Database;
NSMutableArray *columnNames = [NSMutableArray array];
int openDatabaseResult = sqlite3_open([databasePath UTF8String], &sqlite3Database);
if(openDatabaseResult == SQLITE_OK) {
    sqlite3_stmt *compiledStatement;
    NSString *query = [NSString stringWithFormat:@"pragma table_info ('%@')",tableName];
    int prepareStatementResult = sqlite3_prepare_v2(sqlite3Database, [query UTF8String], -1, &compiledStatement, NULL);
    if(prepareStatementResult == SQLITE_OK) {
        sqlite3_stmt* statement;
        int retVal = sqlite3_prepare_v2(sqlite3Database,
                                        [query UTF8String],
                                        -1,
                                        &statement,
                                        NULL);

        if ( retVal == SQLITE_OK )
        {
            while(sqlite3_step(statement) == SQLITE_ROW )
            {
                NSString *value = [NSString stringWithCString:(const char *)sqlite3_column_text(statement, 1)
                                                     encoding:NSUTF8StringEncoding];
                [columnNames addObject:value];
            }
        }
        sqlite3_clear_bindings(statement);
        sqlite3_finalize(statement);
        sqlite3_close(sqlite3Database);
        return [columnNames mutableCopy];
    }



}
sqlite3_close(sqlite3Database);
return nil;

}