通过SQLIte数据库访问对象

时间:2011-06-20 15:47:38

标签: iphone objective-c ios ipad sqlite

我正在将对象传递给我正在执行查询的方法。我的方法是:

-(BOOL)searchWordInDatabase:(NSString *)string
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory= [paths objectAtIndex:0];
NSString *path=[documentsDirectory stringByAppendingPathComponent:@"SymbolTalkLanguageElement.sqlite"];

//Open the database
//might have to make database as property
if(sqlite3_open([path UTF8String], &dataBase) ==SQLITE_OK)
{
    const char *sql="select ImageName from tblLanguageElement where Category= string";
    sqlite3_stmt *statement;

    if(sqlite3_prepare(dataBase, sql, -1, &statement, NULL) == SQLITE_OK)
    {
        while (sqlite3_step(statement) == SQLITE_ROW) 
        {
            NSLog(@"%@",[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]);
            //[list addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]];
            return YES;
        }

    }



}
return NO;

}

但是我没有在查询中获得String的值。我该怎么办?

2 个答案:

答案 0 :(得分:2)

您的查询中存在错误。你无法替换那样的字符串。按以下方式进行。

NSString *sqlStr = [NSString stringWithFormat:@"select ImageName from tblLanguageElement where Category = '%@'", string];
char *sql = (char *)[sqlStr UTF8String];

答案 1 :(得分:1)

确保您的数据库存在于您检索的路径中。您可以在执行语句时按如下方式绑定字符串变量。

 const char *sql = "select ImageName from tblLanguageElement where Category = ?";
 sqlite3_stmt *statement;
 if(sqlite3_prepare(dataBase, sql, -1, &statement, NULL) == SQLITE_OK)
 {
      sqlite3_bind_text(statement, 1, [string UTF8String], -1, SQLITE_TRANSIENT);

      while (sqlite3_step(statement) == SQLITE_ROW) 
      {
           NSLog(@"%@",[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]);
           //[list addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]];
        return YES;
      }
 }