SQLite,Objective C:方法返回int max value

时间:2013-06-01 06:57:41

标签: objective-c cocoa-touch sqlite

-(int)countTheNumberOfDublicatesForType:(int)typeID
{
NSInteger quantity=0;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:user_data];
sqlite3* database = NULL;
sqlite3_stmt *statement;

if(sqlite3_open([path UTF8String], &database) == SQLITE_OK)
{
    const char *sqlQuery=sqlite3_mprintf("SELECT COUNT(refID)\
                                         FROM dublicates\
                                         WHERE typeREF=%i",typeID);

    if(sqlite3_prepare_v2(database, sqlQuery,-1, &statement, NULL) == SQLITE_OK)
        sqlite3_bind_int(statement, 1,typeID);

        if(sqlite3_step(statement) == SQLITE_ROW)
        {
            quantity = sqlite3_column_int(statement, 0);
        }

        sqlite3_finalize(statement);
        sqlite3_free((char*)sqlQuery);
        sqlite3_close(database);
}
else
{
    //
}

return quantity;
}

此方法中的数学运算返回int的最大值。哪个是错误以及如何管理它从db返回实际值的方式?提前谢谢。

编辑:enter image description here

1 个答案:

答案 0 :(得分:0)

您没有错误处理,您绑定到不存在的参数,代码缩进错误,并且您正在使用错误的数据类型进行读取。

使用类似的东西:

if (sqlite3_open([path UTF8String], &database) != SQLITE_OK) {
    sqlite3_errmsg(database); // log or print this
    sqlite3_close(database);
    return 0;
}
if (sqlite3_prepare_v2(database,
                       "SELECT COUNT(refID) FROM dublicates WHERE typeREF=?",
                       -1, &statement, NULL) != SQLITE_OK) {
    sqlite3_errmsg(database); // log or print this
    sqlite3_close(database);
    return 0;
}
sqlite3_bind_int(statement, 1, typeID);
if (sqlite3_step(statement) != SQLITE_ROW)
    sqlite3_errmsg(database); // log or print this
else
    quantity = sqlite3_column_int(statement, 0);
sqlite3_finalize(statement);
sqlite3_close(database);