我需要从sqlite数据库中动态获取表名。
我的代码
-(void) readItemsFromDatabaseforTable:(NSString *)tableName {
// Setup the database object
sqlite3 *database;
// Init the animals Array
itemsList = [[NSMutableArray alloc] init];
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "select * from %@",tableName ;
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSInteger aDescription =(compiledStatement, 2);
// NSString *aImageUrl = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
// Create a new animal object with the data from the database
Category *item = [[Category alloc] initWithName:aName Quantity:aDescription];
// Add the animal object to the animals Array
[itemsList addObject:item];
[item release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
但我没有得到。
我收到一个警告未使用的变量tableName。
实际字符串是const char * sqlStatement =“select * from allcategories”;
如何在该类别中动态传递该表名。
任何人都可以帮助我。
提前感谢你。
答案 0 :(得分:3)
试试这个,
NSString *sql_str = [NSString stringWithFormat:@"select * from %@", tableName];
const char *sqlStatement = (char *)[sql_str UTF8String];
答案 1 :(得分:0)
const char *sqlStatement = "select * from %@",tableName ;
将此行更改为:
const char *sqlStatement = [NSString stringWithFormat: @"select * from %@",tableName];
更好的选择是将此sqlStatement
设为字符串,因为我不知道char是否可以存储NSString
对象...
尝试:
NSString *sqlStatement = [NSString stringWithFormat:@"select * from %@",tableName];
这肯定会有效,我自己尝试过(如果你的tableName
是正确的话)。
NSLog tableName
以查看您是否传递了正确的表名。
希望这有帮助。
答案 2 :(得分:0)
const char *sqlStatement = "select * from %@",tableName ;
将上一行更改为
const char *sqlStatement = (const char *) [[NSString stringWithFormat:@"select * from %@", tableName] UTF8String];