获取Sqlite数据库中的表名和字段名

时间:2021-04-26 13:46:09

代码很简略,没有添加太多的保护


NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"database_name"];
    
    sqlite3 *database;
    sqlite3_open([path UTF8String], &database);
    
    char *errorMsg;
    const char *createSQL = "CREATE TABLE IF NOT EXISTS PEOPLE (ID INTEGER PRIMARY KEY AUTOINCREMENT, FIELD_DATA TEXT)";
    int result = sqlite3_exec(database, createSQL, NULL, NULL, &errorMsg);
    
    sqlite3_stmt *statement;
    if (result == SQLITE_OK) {
        const char *getTableInfo = "select * from sqlite_master where type='table' order by name;";
        result = sqlite3_prepare_v2(database, getTableInfo, -1, &statement, nil);
       while (sqlite3_step(statement) == SQLITE_ROW) {
            char *nameData = (char *)sqlite3_column_text(statement, 1);
            NSString *tableName = [[NSString alloc] initWithUTF8String:nameData];
            NSLog(@"name:%@",tableName);
        }
        
        const char *getColumn = "PRAGMA table_info(PEOPLE)";
        result = sqlite3_prepare_v2(database, getColumn, -1, &statement, nil);
        while (sqlite3_step(statement) == SQLITE_ROW) {
            char *nameData = (char *)sqlite3_column_text(statement, 1);
            NSString *columnName = [[NSString alloc] initWithUTF8String:nameData];
            NSLog(@"columnName:%@",columnName);
        }
        
        sqlite3_finalize(statement);
    }
    sqlite3_close(database);


指出一点:

sqlite_master表结构
CREATE TABLE sqlite_master (
  type TEXT,
  name TEXT,
  tbl_name TEXT,
  rootpage INTEGER,
  sql TEXT
);