我使用sqlite数据库开发应用程序,我需要从表中获取单行。我试过这个:
-(void)getRowFromTableNamed:(NSString *)tableName
whichRow:(NSString *)row
{
NSString *qsql = [NSString stringWithFormat:
@"SELECT %@ FROM %@",
row, tableName];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, [qsql UTF8String], -1, &statement, nil) == SQLITE_OK) {
if (sqlite3_step(statement) == SQLITE_OK) {
char *field = (char *) sqlite3_column_text(statement, 0);
NSString *fieldStr = [[NSString alloc] initWithUTF8String:field];
self.dataString = fieldStr;
[fieldStr release];
}
sqlite3_finalize(statement);
}
}
但它不起作用。所有其他方法都很完美。有人可以帮忙吗?
是的,我删除分号和单引号的事实并没有解决任何问题。是的,它在sqlite3_prepare_v2上失败了。
答案 0 :(得分:0)
我最近和SQLite合作过,所以这只是我的经验猜测... 在SELECT查询中,删除分号。
"SELECT %@ FROM '%@'"
答案 1 :(得分:0)
为什么要首先动态访问表名?我建议使用更安全的方法,并使用带参数的预准备语句,并将响应转换为模型对象,如下所示:
- (NSMutableArray *) getWidgets
{
NSMutableArray *widgets = [[NSMutableArray alloc] init];
sqlite3 *db;
@try
{
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"widgetDb.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
NSLog(@"Cannot locate database file '%@'.", dbPath);
if(sqlite3_open([dbPath UTF8String], &db) != SQLITE_OK)
NSLog(@"An error has occured.");
const char *sql = "SELECT id, name, description FROM widgets";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare_v2(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
NSLog(@"Problem with prepare statement");
Widget *widget;
while (sqlite3_step(sqlStatement)==SQLITE_ROW)
{
widget = [[Widget alloc]init];
widget.id = [NSNumber numberWithInt: (int)sqlite3_column_int(sqlStatement, 0)];
widget.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 1)];
widget.description = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 2)];
[widgets addObject:widget];
}
}
@catch (NSException *exception)
{
NSLog(@"An exception occured: %@", [exception reason]);
}
@finally
{
return widgets;
}
}