【问题标题】:XCode sqlite3 - SELECT always return SQLITE_DONEXCode sqlite3 - SELECT 总是返回 SQLITE_DONE
【发布时间】:2011-01-13 13:02:13
【问题描述】:

经过一天的头撞后,这里的菜鸟寻求帮助....

我正在开发一个带有一个数据库和两个表的 sqlite3 数据库的应用程序。我现在已经到了一个步骤,我想从带有参数的表中进行选择。代码在这里:

-(NSMutableArray*) getGroupsPeopleWhoseGroupName:(NSString*)gn;{

 NSMutableArray *groupedPeopleArray = [[NSMutableArray alloc] init];

 const char *sql = "SELECT * FROM Contacts WHERE groupName='?'";

 @try { 
     NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);  
     NSString *docsDir = [paths objectAtIndex:0];  
     NSString *theDBPath = [docsDir stringByAppendingPathComponent:@"ContactBook.sqlite"];

     if (!(sqlite3_open([theDBPath UTF8String], &database) == SQLITE_OK))
     { NSLog(@"An error opening database."); }

     sqlite3_stmt *st;
     NSLog(@"debug004 - sqlite3_stmt success.");   

     if (sqlite3_prepare_v2(database, sql, -1, &st, NULL) != SQLITE_OK)
     { NSLog(@"Error, failed to prepare statement."); }

     //DB is ready for accessing, now start getting all the info.
     while (sqlite3_step(st) == SQLITE_ROW)
     {   

        MyContacts * aContact = [[MyContacts alloc] init];

        //get contactID from DB.
        aContact.contactID = sqlite3_column_int(st, 0);

        if (sqlite3_column_text(st, 1) != NULL)
        { aContact.firstName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(st, 1)]; }
        else { aContact.firstName = @""; }

        // here retrieve other columns data ....

       //store these info retrieved into the newly created array.
       [groupedPeopleArray addObject:aContact];

       [aContact release];

    }

    if(sqlite3_finalize(st) != SQLITE_OK)
    { NSLog(@"Failed to finalize data statement."); }

    if (sqlite3_close(database) != SQLITE_OK)
    { NSLog(@"Failed to close database."); }

    }

 @catch (NSException *e) {
 NSLog(@"An exception occurred: %@", [e reason]);
 return nil;  }

 return groupedPeopleArray;}

MyContacts 是我放置所有记录变量的类。

我的问题是 sqlite3_step(st) 总是返回 SQLITE_DONE,所以我永远无法获得 myContacts。 (我通过检查返回值验证了这一点)。

我在这里做错了什么?

提前非常感谢!

【问题讨论】:

    标签: iphone xcode sqlite


    【解决方案1】:

    我认为你没有绑定值,如果不使用这个

    sqlite3_bind_text(stmt, 1, [groupName UTF8String], -1, SQLITE_STATIC);
    

    【讨论】:

      【解决方案2】:

      您没有将任何值绑定到您的语句。

      您实际上是在执行 SELECT * FROM Contacts WHERE groupName='?'照原样。

      这可能会返回一个空集,这就是为什么 sqlite3_step 返回 SQLITE_DONE 的原因,该集中没有什么可读取的,你已经完成了。

      This page 有一个将参数绑定到语句的示例..

      编辑:另外,你不需要引号?

      SELECT * FROM Contacts WHERE groupName=?

      然后使用 sqlite3_bind_text

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多