Mr.Noob
Mr.Noob

Reputation: 1005

how to retrieve data from sqlite using WHERE clause iOS 8

I'm very new to IOS programming and I'm having an issue retrieving some data from my database. It's a simple login page that I have done on my application. I need to check if the username exists and It seems to fail at the following line sqlite3_step(statement) == SQLITE_ROW and I also seem to get a warning in the line where I'm writing my sql query saying "Data argument not used by format string". Following is my code

 sqlite3_stmt *statement;
    const char *dbpath = [_databasePath UTF8String];

    if(sqlite3_open(dbpath, &_db) == SQLITE_OK){

        NSString *query = [NSString stringWithFormat:@"SELECT USERNAME,PASSWORD FROM UserInfo WHERE USERNAME = \"%%@\"", self.txtUsername.text];
        const char *query_statement = [query UTF8String];

        if(sqlite3_prepare_v2(_db, query_statement, -1, &statement, NULL) == SQLITE_OK){
            if(sqlite3_step(statement) == SQLITE_ROW){

                NSString *username = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
                NSString *password = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];

                if([username isEqualToString:self.txtUsername.text] && [password isEqualToString:self.txtPassword.text])
                {
                    [self showUIAlertWithMessage:@"Successfully logged in" andTitle:@"Message"];
                    [self shouldPerformSegueWithIdentifier:@"Login" sender:self];
                }
            }
            else{

                [self showUIAlertWithMessage:@"Username not found" andTitle:@"Message"];
            }
        }
        sqlite3_finalize(statement);
        sqlite3_close(_db);
    }

Upvotes: 0

Views: 1499

Answers (1)

trojanfoe
trojanfoe

Reputation: 122381

The format specifier for NSString is %@ and not %%@ (actually any NSObject-derived class that implements the description method).

Using %% escapes the specifier so it will generate the literal sequence %@ in your case.

NOTE: Consider using bind variables which will avoid possible SQL-injection attacks.

NOTE 2: This test is redundant, given the database will have already done it:

[username isEqualToString:self.txtUsername.text]

Upvotes: 1

Related Questions