iOS 下获取 sqlite 数据库的表名和表的字段名

时间:2021-04-26 13:46:33
    NSString *path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"branddb.sqlite"];

sqlite3 *database;
sqlite3_open([path UTF8String], &database);

sqlite3_stmt *statement;
const char *getTableInfo = "select * from sqlite_master where type='table' order by name";
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(menu)";
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);


/****************************华丽的分割线********************************/

关键代码:

查询数据库内的表名

select * from sqlite_master where type='table' order by name


/****************************华丽的分割线********************************/

查询表内的字段名

PRAGMA table_info(menu)


注:当前代码查询的是 menu表的字段名