sqlite3_step始终返回SQLITE_DONE

时间:2014-11-11 07:01:52

标签: ios xcode sqlite

我试图从单个表sqlite数据库中检索数据,但是(sqlite3_step(statement)== SQLITE_ROW)总是返回false。我已手动检查数据库中的值并且它们已存在。这是完整的代码:

-(NSArray *)findByPartNumber:(NSString *)partNumber
{
    const char *dbpath = [databasePath UTF8String];
    NSMutableArray *resultArray = [[NSMutableArray alloc] init];
    if(sqlite3_open(dbpath, &database) == SQLITE_OK)
    {
        NSString *querySQL = [NSString stringWithFormat:@"SELECT Description, ListPrice FROM PriceList WHERE PartNumber=?"];
        const char *query_stmt = [querySQL UTF8String];
        if(sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK)
        {
            sqlite3_bind_text(statement, 1, [partNumber UTF8String], -1, SQLITE_STATIC);
            if(sqlite3_step(statement) == SQLITE_ROW)
            {
                NSString *description;
                NSString *listPrice;

                const char *tmp1 = (const char *)sqlite3_column_text(statement, 0);
                const char *tmp2 = (const char *)sqlite3_column_text(statement, 1);

                if(tmp1 == NULL)
                    description = nil;
                else
                {
                    description = [[NSString alloc] initWithUTF8String:tmp1];
                    [resultArray addObject:description];
                }
                if(tmp2 == NULL)
                    listPrice = nil;
                else
                {
                    listPrice = [[NSString alloc] initWithUTF8String:tmp2];
                    [resultArray addObject:listPrice];
                }
                sqlite3_finalize(statement);
            }
        }
        sqlite3_close(database);
    }

    if([resultArray count] == 0)
        return nil;
    else
        return resultArray;
}

代码进入sqlite3_prepare_v2块,但跳过sqlite3_step块。我错过了什么吗?

2 个答案:

答案 0 :(得分:1)

您的实施存在问题。

你写得像:

sqlite3_bind_text(statement, 1, [partNumber UTF8String], -1, SQLITE_STATIC);
if(sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
   ...
}

您只能将值绑定到预准备语句,因此请将上述代码更改为:

if(sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
   sqlite3_bind_text(statement, 1, [partNumber UTF8String], -1, SQLITE_STATIC);
   ...
}

答案 1 :(得分:-1)

结果是sqlite3_step总是返回SQLITE_DONE,因为没有数据。我错误地设置了databasePath。

代码不正确:

NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent: @"databaseName.sqlite"]];

正确的代码:

databasePath = [[NSBundle mainBundle] pathForResource:@"databaseName" ofType:@"sqlite"];