Show: Delphi C++
Display Preferences

Tutorial: Connecting to a SQLite Database (Delphi)

From RAD Studio
Jump to: navigation, search

Go Up to Tutorials#SQLite and SQLMonitor

This tutorial is a simple Delphi VCL Form application that shows how to establish a connection to a SQLite database and execute a simple query.

In this example an SQLite database is used, but you can use any SQLite database available to you. The database used in this example is located at D:\test.s3db and has one table named example.

Steps

  1. Select File > New > VCL Forms Application - Delphi.
  2. Add the following components to the form:
At this point the form should look like this:

SQLiteTutorialForm.png

3. Add the following code to the OnClick event handler for the connectButton.
procedure TForm3.connectButtonClick(Sender: TObject);
begin
  // Set the path of your database file.
  // Replace "full_path_to_your_database_file" with the absolute path 
  // to your SQLite database file.
  SQLConnection1.Params.Add('Database=full_path_to_your_database_file');
  try
    // Establish the connection.
    SQLConnection1.Connected := true;
    executeButton.Enabled := true;
    outputMemo.Text := 'Connection established!';
  except
    on E: EDatabaseError do
      ShowMessage('Exception raised with message' + E.Message);
  end;
end;
4. Add the following code to the OnClick event handler for the executeButton.
procedure TForm3.executeButtonClick(Sender: TObject);
var
  results: TDataSet;
  query: String;
begin
  outputMemo.Clear;
  // A random query
  query := 'SELECT * FROM example;';
 
  try
  // Execute the query on the database.
    SQLConnection1.Execute(query, nil, results);
  except
    on E: Exception do
      outputMemo.Text := 'Exception raised with message: ' + E.Message;
  end;
  // Show the results of the query in a TMemo control.
  ShowSelectResults(results);
end;
Here is the code for the ShowSelectResults procedure:
procedure TForm3.ShowSelectResults(results: TDataSet);
var
  names: TStringList;
  i: Integer;
  currentField: TField;
  currentLine: string;
begin
  if not results.IsEmpty then
  begin
    results.First;
    names := TStringList.Create;
    results.GetFieldNames(names);
    while not results.Eof do
    begin
      currentLine := '';
      for i := 0 to names.Count - 1 do
      begin
        currentField := results.FieldByName(names[i]);
        currentLine := currentLine + ' ' + currentField.AsString;
      end;
      outputMemo.Lines.Add(currentLine);
      results.Next;
    end;
  end;
end;

Uses


See Also

Personal tools
In other languages