我有一个方法,它从数据库生成返回值的字典:
- (NSDictionary *)getParametersForPreset:(NSUInteger)presetID plants:(NSArray *)plants
{
NSString *loggers = @"";
NSString *invertors = @"";
NSString *plantsList = @"";
const char *sql = "SELECT loggerID, invertorID FROM records WHERE presetID IN (?) AND plantID IN (?)";
BOOL isEmpty = YES;
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) != SQLITE_OK)
{
NSLog(@"Error: '%s'.", sqlite3_errmsg(database));
}
for (int i = 0; i < [plants count]; i++) {
if (i == 0)
{
plantsList = [NSString stringWithFormat:@"'%@'",[[plants objectAtIndex:0] valueForKey:@"id"]];
}
else
{
plantsList = [plantsList stringByAppendingFormat:@",'%@'",[[plants objectAtIndex:i] valueForKey:@"id"]];
}
}
NSLog(@"plants: %@", plantsList);
NSLog(@"preset: %d", presetID);
sqlite3_bind_int(statement, 1, presetID);
sqlite3_bind_text(statement, 2, [plantsList UTF8String], -1, SQLITE_TRANSIENT);
NSMutableDictionary *dictionary = [[[NSMutableDictionary alloc] init] autorelease];
int i = 0;
while (sqlite3_step(statement) == SQLITE_ROW)
{
if (i == 0)
{
loggers = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
invertors = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
isEmpty = NO;
i++;
}
else
{
loggers = [loggers stringByAppendingFormat:@",%@",[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]];
invertors = [invertors stringByAppendingFormat:@",%@",[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)]];
}
}
sqlite3_reset(statement);
if (isEmpty == YES)
{
return nil;
}
[dictionary setValue:[NSString stringWithString:[plantsList stringByReplacingOccurrencesOfString:@"'" withString:@""]] forKey:@"plants"];
[dictionary setValue:loggers forKey:@"loggers"];
[dictionary setValue:invertors forKey:@"invertors"];
return dictionary;
}
此查询在代码中没有返回任何内容,但随后我在Firefox的SQLite Manager中为同一个数据库执行相同的查询,它返回正确的数据。拜托,帮我找错,我真的很累。
以下是我在Manager中的查询:
SELECT loggerID, invertorID FROM records WHERE presetID=1 AND plantID IN ('3','2','1','6','5','4')
以下是代码中的记录值:
preset: 1
plants: '3','2','1','6','5','4'
非常感谢!
答案 0 :(得分:1)
我最近一直致力于类似的查询。
我有一个存储ID列表的NSMutableArray。我使用函数componentsJoinedByString将它们作为字符串连接起来。
然后我有一个NSString对象,它使用stringWithFormat函数保存我的SQL语句。
因此,生成SQLite查询的代码可以是:
NSString * query = [NSString stringWithFormat:@"SELECT loggerID, invertorID FROM records WHERE presetID IN (%d) AND plantID IN (%@)",presetID,[plantsList componentsJoinedByString:@","]];
希望这有帮助。