チュートリアル:VCL アプリケーションから SQLite データベースに接続する

提供: RAD Studio
移動先: 案内検索

データベースおよび LiveBinding のチュートリアル への移動


このチュートリアルでは、単純な VCL フォーム アプリケーションを使って、SQLite データベースへの接続を確立し簡単なクエリを実行する方法を説明します。

この例では Embarcadero から提供しているデータベースを使用していますが、どのような SQLite データベースでも使用できます。この例で使用するデータベースは次の場所にあります。

  • Windows の場合: C:\Users\Public\Documents\Embarcadero\Studio\19.0\Samples\Data\Employees.s3db

このデータベースには、Employee という名前の 1 つのテーブルと、フィールドを持ついくつかのタプルが含まれています。ここでは、データベースに接続し、Employee テーブル内のすべてのタプルを表示します。

手順

  1. [ファイル|新規作成|VCL フォーム アプリケーション - Delphi]、または [VCL フォーム アプリケーション - C++Builder]を選択します。
  2. フォームに以下のコンポーネントを追加します。
3. この時点で、フォームは次のようになっています。
VLCSQLiteTutorialForm.png
4. connectButtonOnClick イベント ハンドラに以下のコードを追加します。
メモ: "full_path_to_your_database_file" は使用するデータベース ファイルの絶対パスに置き換えてください。
Delphi の場合:
procedure TDemonstration.connectButtonClick(Sender: TObject);
begin
  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;
C++ の場合:
void __fastcall TDemonstration::connectButtonClick(TObject *Sender)
{
 // Use double backslash in Windows Paths as the backslash character (\) must be escaped with another one to be treated literally.
	SQLConnection1->Params->Add("Database=full_path_to_your_database_file");
	try
	{
		// Establish the connection.
		SQLConnection1->Connected = true;
		executeButton->Enabled = true;
		outputMemo->Text = "Connection established!";
	}
	catch (EDatabaseError& E)
	{
	   ShowMessage("Exception raised with message" + E.Message);
	}

}
5. executeButtonOnClick イベント ハンドラに以下のコードを追加します。
Delphi の場合:
procedure TDemonstration.executeButtonClick(Sender: TObject);
var
  query: String;
begin
  outputMemo.ClearSelection;
  // A random query
  query := 'SELECT * FROM Employee;';
  try
  // Assign the query to the object SQLQuery1.
    SQLQuery1.SQL.Text := query;
    SQLQuery1.Active := true;
  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();
end;
C++ の場合:
void __fastcall TDemonstration::executeButtonClick(TObject *Sender)
{
	String query;

	outputMemo->ClearSelection();
	// A random query
	query = "SELECT * FROM Employee;";
	try
	{
		// Assign the query to the object SQLQuery1.
		 SQLQuery1->SQL->Text = query;
		 SQLQuery1->Active = true;
	}
	catch (Exception& E)
	{
		outputMemo->Text = "Exception raised with message" + E.Message;
	 }
	// Show the results of the query in a TMemo control.
	 ShowSelectResults();
}
以下は ShowSelectResults 手続きのコードです。
Delphi の場合:
procedure TDemonstration.ShowSelectResults();
var
  names: TStringList;
  i: Integer;
  currentField: TField;
  currentLine: string;
begin
  if not SQLQuery1.IsEmpty then
  begin
    SQLQuery1.First;
    names := TStringList.Create;
    try
      SQLQuery1.GetFieldNames(names);
      while not SQLQuery1.Eof do
      begin
        currentLine := '';
        for i := 0 to names.Count - 1 do
        begin
          currentField := SQLQuery1.FieldByName(names[i]);
          currentLine := currentLine + ' ' + currentField.AsString;
        end;
        outputMemo.Lines.Add(currentLine);
        SQLQuery1.Next;
      end;
    finally
      names.Free;
    end;
  end;
end;
メモ: procedure ShowSelectResults(); を宣言するのを忘れないでください。
C++ の場合:
void __fastcall TDemonstration::ShowSelectResults()
{
	TStringList* names;
	TField* currentField;
	String currentLine;

	if (!SQLQuery1->IsEmpty()) {
	  SQLQuery1->First();
	  names = new TStringList
	  __try{
	    SQLQuery1->GetFieldNames(names);
	    while (!SQLQuery1->Eof) {
		  currentLine = "";
		  for (int i = 0; i < names->Count; ++i) {
			currentField = SQLQuery1->FieldByName(names->Strings[i]);
			currentLine = currentLine + " " + currentField->AsString;
		  }
		   outputMemo->Lines->Add(currentLine);
		   SQLQuery1->Next();
	    }
	  }
	}
	  __finally {
	    names->Free();
	  }
}
メモ: プロジェクトの Unit.h で、void __fastcall TDemonstration::ShowSelectResults(); と宣言するのを忘れないでください。
6. アプリケーションを実行し、まず[Connect]ボタンを、それから[Execute]ボタンをクリックすると、アプリケーションは次のように表示されます。
VLCSQLiteTutorialApp.png

メモ: Windows で SQLite データベースに接続するためには、ライブラリ sqlite3.dll を以下のシステム パスに置いて、アプリケーションから sqlite3.dll を見つけられるようにしてください。

  • 32 ビット版 Windows の場合: C:\Windows\System32
  • 64 ビット版 Windows の場合: C:\Windows\SysWOW64

使用する API

関連項目