user931018
user931018

Reputation: 703

Searching database for existing record problems

I'm making a program which has a registration page and saved the data to a database. I'm trying to verify the username so that there won't be people with the same username.. The username is also the primary key in my database.. When I click the submit button the program either just freezes or give me the following error message: "Exception class EOIeException with message 'The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field that contain duplicate data, remove index, or redefine the index to permit duplicate entries and try again"

I am using the following code to search if the edit box text appears in the database and if it does that it should display a message box.. But instead it gives me the error as said above.

with dmPredictGame do
    while NOT tblUserInfo.EOF do
    begin
      tblUserInfo.First;
      if Uppercase(edtUsername.Text) = tblUserInfo['Username'] then
        begin
          MessageDlg('The username "' + edtUsername.Text + '" already exists!', mtError, [mbOK], 0);
          edtusername.SetFocus;
          exit;
        end
      else
        tblUserInfo.Next;
        tblUserInfo.Close
    end;

Upvotes: 2

Views: 413

Answers (1)

Marcus Adams
Marcus Adams

Reputation: 53830

To search using your method, be sure to put the First outside the loop, otherwise you'll keep starting over, and never finish:

// Go to the beginning
tblUserInfo.First;
while NOT tblUserInfo.EOF do
begin
  // Set both to upper so they match
  // Use FieldByName (it's not an array)
  if Uppercase(edtUsername.Text) = Uppercase(tblUserInfo.FieldByName('Username').AsString) then
  begin
    MessageDlg('The username "' + edtUsername.Text + '" already exists!', mtError, [mbOK], 0);
    edtUsername.SetFocus;
    Exit;
  end;
  tblUserInfo.Next;
end;

However, for searches, you should consider using Locate:

if tblUserInfo.Locate('UserName', edtUserName.Text, [loCaseInsensitive]) then
begin
  // Username exists
end;

Upvotes: 4

Related Questions