我想將個人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 } }