我想将个人iPhone应用程序迁移到新的数据库版本。 因为我没有保存某些版本,所以须要检查某些列名称是否存在。 sql
该Stackoverflow条目建议进行选择 数据库
SELECT sql FROM sqlite_master WHERE tbl_name = 'table_name' AND type = 'table'
并解析结果。 spa
这是常见的方式吗? 备择方案? code
若是要搜索任何特定列,则能够使用Like语句 orm
例如: sqlite
SELECT * FROM sqlite_master where sql like('%LAST%')
-(NSMutableDictionary*)tableInfo:(NSString *)table { sqlite3_stmt *sqlStatement; NSMutableDictionary *result = [[NSMutableDictionary alloc] init]; const char *sql = [[NSString stringWithFormat:@"pragma table_info('%s')",[table UTF8String]] UTF8String]; if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK) { NSLog(@"Problem with prepare statement tableInfo %@",[NSString stringWithUTF8String:(const char *)sqlite3_errmsg(db)]); } while (sqlite3_step(sqlStatement)==SQLITE_ROW) { [result setObject:@"" forKey:[NSString stringWithUTF8String:(char*)sqlite3_column_text(sqlStatement, 1)]]; } return result; }
为了获取列信息,您能够使用如下代码段: ci
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); }
//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; }
只为像我这样的超级菜鸟想知道人们的意思或含义 get
PRAGMA table_info('table_name')
您但愿将其用做您的prepare语句,以下所示。 这样作会选择一个看起来像这样的表,但其中会填充与该表有关的值。 string
cid name type notnull dflt_value pk ---------- ---------- ---------- ---------- ---------- ---------- 0 id integer 99 1 1 name 0 0
其中id和name是您的列的实际名称。 所以,要获取该值,您须要使用如下方法选择列名称: it
//returns the name sqlite3_column_text(stmt, 1); //returns the type sqlite3_column_text(stmt, 2);
它将返回当前行的列名。 要抓住它们,或者找到您想要的一个,您须要遍历全部行。 最简单的方法以下。
//where rc is an int variable if wondering :/ rc = sqlite3_prepare_v2(dbPointer, "pragma table_info ('your table name goes here')", -1, &stmt, NULL); if (rc==SQLITE_OK) { //will continue to go down the rows (columns in your table) till there are no more while(sqlite3_step(stmt) == SQLITE_ROW) { sprintf(colName, "%s", sqlite3_column_text(stmt, 1)); //do something with colName because it contains the column's name } }