如何比较数据库中的数据?

时间:2011-09-13 14:07:34

标签: iphone sql database compiler-construction

我已经创建了一个数据库。在我看来,我正在检查提供的数据是否已经存在。如果存在则返回是否则否。为此,我使用此代码..

 +(BOOL)compareDataInDB:(NSString *)Start_text EndAddress:(NSString *)End_text Categories:(NSString *)Category_text{


BOOL flag=FALSE;

if(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK) {
    //int LastId="select Max(place_id) from Places";
    //      NSLog(@"%i",LastId);
    const char *sql = "select * from Places where Start_text = Start_text  and End_text = End_text and Category_text = Category_text";
    sqlite3_stmt *stmt;
    int rtnVal = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if( rtnVal == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            flag=TRUE;

        }
    }
    sqlite3_finalize(stmt);
}
sqlite3_close(db);

if(flag==TRUE)
    return YES;
else
    return NO;

}

按钮操作我已使用此代码

-(IBAction)Find{
  BOOL tmp=[GlobalClass compareDataInDB:txtstart.text EndAddress:txtend.text   Categories:txtCategory.text];
    if(tmp)
    [GlobalClass storeDataInDB:txtstart.text EndAddress:txtend.text Categories:txtCategory.text];
    else 
        NSLog(@"exsit data in database");
}

现在问题是它总是返回否。这段代码中的错误是什么?以及如何从数据库中压缩数据?

提前致谢...

2 个答案:

答案 0 :(得分:1)

您必须为SQL语句使用以下代码。

NSString *tempSQL = [[NSString alloc] initWithFormat:@"select * from Places where Start_text = '%@'  and End_text = '%@' and Category_text = '%@'", Start_text, Start_text, Category_text];
const char *sql = [tempSQL cStringUsingEncoding:NSUTF8StringEncoding];
[tempSQL release];

答案 1 :(得分:0)

+(BOOL)compareDataInDB:(NSString *)Start_text EndAddress:(NSString *)End_text Categories:NSString *)Category_text
{       
    BOOL flag=NO;

    if(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK) {
        //int LastId="select Max(place_id) from Places";
        //      NSLog(@"%i",LastId);
        const char *sql = "select * from Places where Start_text = Start_text  and End_text = End_text and Category_text = Category_text";
        sqlite3_stmt *stmt;
        int rtnVal = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
        if( rtnVal == SQLITE_OK) 
        {
           sqlite3_bind_text(stmt, 1, [Start_text UTF8String], -1, SQLITE_TRANSIENT);
           sqlite3_bind_text(stmt, 2, [End_text UTF8String], -1, SQLITE_TRANSIENT);
           sqlite3_bind_text(stmt, 3, [Category_text UTF8String], -1, SQLITE_TRANSIENT);

            while (sqlite3_step(stmt) == SQLITE_ROW) {
                flag=YES;
            }
        }
        sqlite3_finalize(stmt);
    }
    sqlite3_close(db);

    return flag;
    }