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
.schema in sqlite console when you have you're inside the table it looks something like this for me ...
sqlite>.schema
CREATE TABLE players(
id integer primary key,
Name varchar(255),
Number INT,
Team varchar(255)
function getDetails(){
var data = [];
dBase.executeSql("PRAGMA table_info('table_name') ", [], function(rsp){
if(rsp.rows.length > 0){
for(var i=0; i<rsp.rows.length; i++){
var o = {
name: rsp.rows.item(i).name,
type: rsp.rows.item(i).type
}
data.push(o);
}
}
alert(rsp.rows.item(0).name);
},function(error){
alert(JSON.stringify(error));
});
}
An alternative way to get a list of column names not mentioned here is to select from a pragma function:
SELECT name FROM PRAGMA_TABLE_INFO('your_table');
name
tbl_name
rootpage
sql
You can check if a certain column exists by running:
SELECT 1 FROM PRAGMA_TABLE_INFO('your_table') WHERE name='sql';
1
This is what you use if you don't want to parse the result of select sql from sqlite_master or pragma table_info.
Reference:
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;
}
In order to get the column information you can use the following snippet:
String sql = "select * from "+oTablename+" LIMIT 0";
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
ResultSetMetaData mrs = rs.getMetaData();
for(int i = 1; i <= mrs.getColumnCount(); i++)
{
Object row[] = new Object[3];
row[0] = mrs.getColumnLabel(i);
row[1] = mrs.getColumnTypeName(i);
row[2] = mrs.getPrecision(i);
}
If you do
.headers ON
you will get the desired result.