2011-07-14 226 views
0

我正在创建一个iOS应用程序,它使用变量从单个SQLITE表中读取数据。当所有变量都被填充时,我没有任何问题,但我希望最终有大量变量,并允许用户跳过他们认为对他们没有意义的变量。换句话说,即使在变量为空或0时,我如何才能完成这项工作,比如忽略select语句的那部分,但继续?我试图使用IF语句或CASE语句,但后来我得到未声明的错误。我可以用IF重复整个getInitialDataToDisplay,但必须有一个更简单的方法。iPhone SQLITE Select语句变量

+ (void) getInitialDataToDisplay:(NSString *)dbPath{ 
int addOne = [[NSUserDefaults standardUserDefaults] integerForKey: @"criterion1key"]; 
int addTwo = [[NSUserDefaults standardUserDefaults] integerForKey: @"criterion2key"]; 
int addThree = [[NSUserDefaults standardUserDefaults] integerForKey: @"criterion3key"];  

if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {  
NSString *querystring= [NSString stringWithFormat:@"select * from animalswhere description > %i and description < %i and cash >= %i",addOne, addTwo, addThree];   //WORKS FINE IF ALL VARIABLES HAVE VALUES, BUT DOES NOTHING IF VARIABLES ARE EMPTY    
const char *sql = [querystring UTF8String];    
sqlite3_stmt *selectstmt; if(sqlite3_prepare_v2(database, sql, -1,&selectstmt, NULL) == SQLITE_OK) 
{      
while(sqlite3_step(selectstmt) == 
SQLITE_ROW) { 

NSInteger primaryKey = sqlite3_column_int(selectstmt, 0); 

    Animal *animal = [[Animal alloc] initWithPrimaryKey:primaryKey]; 
      animal.name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)]; 
      animal.description = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)]; 
     animal.imageURL = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 5)]; 
     animal.cash = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 32)]; 
      [appDelegate.animals addObject:animal];    
[animal release];   
}  
    }  
     }   else  sqlite3_close(database); 
} 
+1

请格式化代码。 –

+1

只有受虐者直接在Objective-C中使用SQLite C API。 [使用FMDB](http://github.com/ccgus/fmdb)(一个SQLite包装器)或[CoreData](http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/CoreData/ cdProgrammingGuide.html)(一个对象图管理器)。 –

回答

0

听起来像是你需要的是使用标记变量/值,和一点点布尔逻辑:

SELECT valuea, valueb, valuec 
FROM table 
WHERE valuea = %inputParmA 
AND (%inputParmB = 0 OR valueb = %inputParmB) 

这将有选择的所有行的效果,其中valuea匹配值的传入(的inputParmA),并且,如果inputParmB非零,valueb匹配inputParmB
您必须根据自己的需要来调整它,但如果这种方法不可用(或难以生成),则它是使用动态sql的一种快速又脏的替代方法。
不完全确定性能,但我有一个查询,其中有几十个,在数百万行数据库上运行,并在一分钟内返回(数百个结果)。

+0

我很抱歉,但我不太明白。 %inputParmA和%inputParmB来自哪里,它是addOne和addTwo吗?如果我去实现这个,我坚持这个到我的NSString * querystring = [NSString stringWithFormat:@“对吗?我需要在NSString之前声明什么? – user845262

+0

是的,对不起,这些最终会成为'addOne'和'addTwo '我习惯于在带有静态语句的AS400上使用DB2,并且必须命名主变量(因为我没有明确地准备一个语句 - 它会自动将它们转换为参数标记等)。可以理解的SQL语法,而不是完全针对你的平台的东西。 –