我想把我的iPhone应用程序迁移到一个新的数据库版本。由于我没有保存一些版本,我需要检查是否存在某些列名。
这个Stackoverflow条目建议执行选择
SELECT sql FROM sqlite_master
WHERE tbl_name = 'table_name' AND type = 'table'
并解析结果。
这是常见的方式吗?选择呢?
我想把我的iPhone应用程序迁移到一个新的数据库版本。由于我没有保存一些版本,我需要检查是否存在某些列名。
这个Stackoverflow条目建议执行选择
SELECT sql FROM sqlite_master
WHERE tbl_name = 'table_name' AND type = 'table'
并解析结果。
这是常见的方式吗?选择呢?
当前回答
获得这里没有提到的列名列表的另一种方法是,从PRAGMA_TABLE_INFO()表值函数中进行选择,这种方法是跨平台的,不依赖于sqlite3.exe shell。
SELECT name FROM PRAGMA_TABLE_INFO('your_table');
name
tbl_name
rootpage
sql
您可以通过查询来检查某个列是否存在:
SELECT 1 FROM PRAGMA_TABLE_INFO('your_table') WHERE name='column1';
1
如果你不想解析select sql from sqlite_master或pragma table_info的结果,你可以使用它。
注意此特性是实验性的,在SQLite 3.16.0(2017-01-02)版本中添加。
参考:
https://www.sqlite.org/pragma.html#pragfunc
其他回答
//JUST little bit modified the answer of giuseppe which returns array of table columns
+(NSMutableArray*)tableInfo:(NSString *)table{
sqlite3_stmt *sqlStatement;
NSMutableArray *result = [NSMutableArray array];
const char *sql = [[NSString stringWithFormat:@"PRAGMA table_info('%@')",table] UTF8String];
if(sqlite3_prepare(md.database, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(@"Problem with prepare statement tableInfo %@",
[NSString stringWithUTF8String:(const char *)sqlite3_errmsg(md.database)]);
}
while (sqlite3_step(sqlStatement)==SQLITE_ROW)
{
[result addObject:
[NSString stringWithUTF8String:(char*)sqlite3_column_text(sqlStatement, 1)]];
}
return result;
}
如果你想要查询的输出包含列名并正确对齐为列,可以在sqlite3中使用这些命令:
.headers on
.mode column
你会得到如下输出:
sqlite> .headers on
sqlite> .mode column
sqlite> select * from mytable;
id foo bar
---------- ---------- ----------
1 val1 val2
2 val3 val4
如果你有sqlite数据库,使用sqlite3命令行程序和这些命令:
列出数据库中所有的表。
.tables
要显示给定表名的模式:
.schema tablename
如果有的话
.headers ON
你会得到你想要的结果。
如果您正在使用SQLite3,则不支持INFORMATION_SCHEMA。使用PRAGMA table_info代替。这将返回关于表的6行信息。要获取列名(row2),使用如下所示的for循环
cur.execute("PRAGMA table_info(table_name)") # fetches the 6 rows of data
records = cur.fetchall()
print(records)
for row in records:
print("Columns: ", row[1])