mercredi 9 décembre 2015

How do I search a SQL database in Delphi?

I wrote a code to search the Postcode column in the database, however the only acceptable search option is simply 'Postcode', not a string like 'N15 6UB'. If I try to search for a string, it comes up with Access Violation error.

The code should search for the 'edtSearch.Text', clear the current grid and display the new data.

 procedure TfrmMain.btnSearchClick(Sender: TObject);
 var
  sql: string;

 begin
  sql := 'SELECT * ';
  sql := sql + 'FROM CustDatabase ';
  sql := sql + 'WHERE Postcode = "' + edtSearch.Text + '" ';
  sql := sql + 'ORDER BY Postcode';
  query.SQL.Text := sql;
  query.Open;
  query.First;

 for i := 0 to 8 do
   sgdDatabases.rows[i].Clear;

 sgdDatabases.colCount := 9;
 sgdDatabases.FixedCols := 0;
 for i := 0 to 8 do
   sgdDatabases.ColWidths[i] := 100;

 sgdDatabases.Cells[0, 0] := 'ID';
 sgdDatabases.Cells[1, 0] := 'First Name';
 sgdDatabases.Cells[2, 0] := 'Last Name';
 sgdDatabases.Cells[3, 0] := 'Address';
 sgdDatabases.Cells[4, 0] := 'Town';
 sgdDatabases.Cells[5, 0] := 'County';
 sgdDatabases.Cells[6, 0] := 'Postcode';
 sgdDatabases.Cells[7, 0] := 'Telephone No.';
 sgdDatabases.Cells[8, 0] := 'E-Mail';

row := 1;
while not query.EOF do
 begin
  ID := query.FieldByName('ID').AsString;
  firstname := query.FieldByName('First Name').AsString;
  lastname := query.FieldByName('Last Name').AsString;
  address := query.FieldByName('Address').AsString;
  town := query.FieldByName('Town').AsString;
  county := query.FieldByName('County').AsString;
  postcode := query.FieldByName('Postcode').AsString;
  telno := query.FieldByName('TelNo').AsString;
  email := query.FieldByName('Email').AsString;

  sgdDatabases.Cells[0, row] := ID;
  sgdDatabases.Cells[1, row] := firstname;
  sgdDatabases.Cells[2, row] := lastname;
  sgdDatabases.Cells[3, row] := address;
  sgdDatabases.Cells[4, row] := town;
  sgdDatabases.Cells[5, row] := county;
  sgdDatabases.Cells[6, row] := postcode;
  sgdDatabases.Cells[7, row] := telno;
  sgdDatabases.Cells[8, row] := email;

  row := row + 1;
  query.Next;

 end;
end;

Aucun commentaire:

Enregistrer un commentaire