Home > Enterprise >  First login attempt works if it's correct, but if it's incorrect then other correct attemp
First login attempt works if it's correct, but if it's incorrect then other correct attemp

Time:02-14

void __fastcall TFormLogin::btnLoginClick(TObject *Sender)
{
    UnicodeString query = "select * from admin where korisnickoIme = '"   editKorisnicko->Text  
                     "' AND lozinka = '"   editLozinka->Text   "'";
    AnsiString ansiQuery = query;

    ADOQuery1->ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=KnjiznicaManagement;Data Source=KUKICRO\\SQLEXPRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=KUKICRO;Use Encryption for Data=False;Tag with column collation when possible=False";
    ADOQuery1->SQL->Add(ansiQuery);

    ADOQuery1->Prepared = true;

    try
    {
        ADOQuery1->Active = true;
    }
    catch (EADOError& e)
    {
        MessageDlg("Error spajanja", mtError,
                      TMsgDlgButtons() << mbOK, 0);
        return;
    }

    TDataSource* Src = new TDataSource(this);
    Src->DataSet = ADOQuery1;
    Src->Enabled = true;

    if(Src->DataSet->RecordCount < 1){
        labelPrijava->Visible = true;
        ADOQuery1->Prepared = false;

        Src->Enabled = false;

        try{
            ADOQuery1->Active = false;
        }
        catch (EADOError& e){
            MessageDlg("Error odspajanja", mtError,
                  TMsgDlgButtons() << mbOK, 0);
        }
        return;
    }

    FormMain->labelUlogiran->Caption = Src->DataSet->FieldByName("korisnickoIme")->AsString;
    FormLogin->Close();
}

Code from above is my OnClick button event code. It should simulate login from a database table "admin" that contains "korisnickoIme" in the username field and "lozinka" in the password field. When I type in the correct username and password, the first attempt works, but if I type in the wrong username and password and then the correct one, it doesn't work. When I go through with the debugger, the last if is true but it shouldn't be.

CodePudding user response:

This line:

ADOQuery1->SQL->Add(ansiQuery);

adds the ansiQuery to the end of the SQL collection for ADOQuery. When you click the button a second time, the new query is added to the end, but the original incorrect query is still at the start of the collection, so it is run first.

Solution: Clear out the collection on each button click. Add the following before the Add line:

ADOQuery1->SQL->Clear()
  • Related