Difference between revisions of "SQLdb Tutorial1/ja"

From Lazarus wiki
Jump to navigationJump to search
Line 58: Line 58:
  
 
=== データベースに接続する ===
 
=== データベースに接続する ===
How can we now show the data from our database on the screen?
+
データベースのデータを画面に表示するにはどうするか?
  
First we need to tell DBConnection where the employee.fdb database is located. Locations of that db differ depending on operating system, it could be something like:
+
まず、DBConnection に、employee.fdb データベースがどこにあるかを伝える必要がある。そのデータベースの場所はオペレーティング システムによって異なる。次のような場所である:
* .../examples/empbuild/ subdirectory of your Firebird installation on Linux
+
* .../examples/empbuild/ Linux 上の Firebird インストールのサブディレクトリ
* C:\Program Files\Firebird\Firebird_2_5\examples\empbuild\EMPLOYEE.FDB on a Windows machine
+
* Windows マシンの場合は C:\Program Files\Firebird\Firebird_2_5\examples\empbuild\EMPLOYEE.FDB
* Using Firebird embedded, the file should be in your project directory
+
* Firebird 埋め込みを使用する場合、ファイルはプロジェクト ディレクトリにある必要がある
  
Again you have the choice: you can use the object inspector to assign the path or do it directly in your source code.
+
ここでも選択が可能だ: オブジェクトインスペクタを使用してパスを割り当てるか、ソースコードで直接行うことができる。
  
We choose to use the object inspector: set the DBConnection 'HostName' property to the Firebird server name or IP adddress. Use localhost if a Firebird server is running on your development machine; use a blank value if you use the embedded Firebird client.
+
オブジェクトインスペクタを使用することを選択する。DBConnection の「HostName」プロパティを Firebird サーバー名または IP アドレスに設定する。 Firebird サーバーが開発マシンで実行されている場合は、localhost を使用します。 埋め込み Firebird クライアントを使用する場合は、空白の値を使用する。
Change the ''DatabaseName'' property of DBConnection to the path to the employee.fdb file on the database server. If you use embedded Firebird, the path part should be empty and you should just specify the filename.
+
DBConnection の ''DatabaseName'' プロパティを、データベース サーバー上のemployee.fdb ファイルへのパスに変更します。埋め込み Firebird を使用する場合、パス部分は空にし、ファイル名のみを指定する必要がある。
  
Before the database server grants access to the data, it will check authorisation via username and password. A serious database application will ask the user for both values when the application is started, and send these to the server when connecting. A possible way of doing this is shown in [[SQLdb Tutorial3]].
+
データベースサーバーはデータへのアクセスを許可する前に、ユーザー名とパスワードによる承認をチェックします。本格的なデータベース アプリケーションは、アプリケーションの起動時に両方の値をユーザーに要求し、接続時にこれらをサーバーに送信する。これを行う可能な方法は [[SQLdb Tutorial3]] に示されている。
  
However, for now, to simplify matters, we use the object inspector again to hard code these. Change the 'UserName' property to 'SYSDBA' and 'Password' to 'masterkey' (of course, adjust if your database installation has a different username/password).
+
ただし、今のところ、問題を単純化するために、オブジェクトインスペクタを再度使用してこれらをハードコーディングします。「UserName」プロパティを「SYSDBA」に変更し、「Password」を「masterkey」に変更する(もちろん、データベースのインストールに別のユーザー名/パスワードがある場合は調整のこと)。
  
Now check if all settings so far are correct: set the 'Connected' property to 'True'. If the database path isn't correct or if username or password are wrong, you will get an error message. If the connection was successful, you should cut it now (set 'Connected' to 'False').
+
ここで、これまでの設定がすべて正しいかどうかを確認する。「Connected」プロパティを「True」に設定します。 データベースのパスが正しくない場合、またはユーザー名またはパスワードが間違っている場合は、エラーメッセージが表示される。接続が成功した場合は、ここで切断する必要があります (「Connected」を「False」に設定する)
  
 
==== PostgreSQL ====
 
==== PostgreSQL ====
The situation with PostgreSQL is very similar to that on Firebird. The database name does not have a path - you just specify a name part (e.g. 'employee'). PostgreSQL has no embedded mode, so you need to fill out the ''HostName'' property for the connection test to work.
+
PostgreSQL の状況は Firebird の状況と非常に似ている。データベース名にはパスがない。名前の部分 (例: 「employee」) を指定するだけです。 PostgreSQL には埋め込みモードがないため、接続テストを機能させるには「HostName」プロパティを入力する必要がある。
  
 
==== SQLite ====
 
==== SQLite ====
For SQLite, you can leave the 'HostName', 'UserName', and 'Password' properties empty. Set the 'DatabaseName' to the name of your SQLite file, e.g. employee.sqlite. Note: sqlite will create the database specified if it doesn't exist, so be careful here.
+
SQLite の場合、「HostName」、「UserName」、および「Password」プロパティを空のままにすることができます。 「DatabaseName」を SQLite ファイルの名前に設定します。従業員.sqlite。注: sqlite は、指定されたデータベースが存在しない場合にそれを作成するため、ここでは注意のこと。
  
You should now have something like the following screenshot - todo: this screenshot is actually further along, we only have a button now:
+
次のスクリーンショットのようなものが表示されるはずだ - todo: このスクリーンショットは実際にはさらに進んでおり、現在はボタンだけがある。
 
[[Image:SQLTut1ComponentsSetUp.png|framed|center|Form and components set up]]
 
[[Image:SQLTut1ComponentsSetUp.png|framed|center|Form and components set up]]
 +
 +
DBGrid のプロパティ「Options」→「dgDisplayMemoText」を「(True)」に変更する。 それ以外の場合は、すべてのデータ フィールドに (MEMO) が表示される。
  
 
=== どのデータを表示するか選択する ===
 
=== どのデータを表示するか選択する ===

Revision as of 13:01, 28 March 2024

Deutsch (de) English (en) español (es) français (fr) 日本語 (ja) 中文(中国大陆)‎ (zh_CN)

データベースのポータル

参照:

チュートリアル/練習となる記事:

各種データベース

Advantage - MySQL - MSSQL - Postgres - Interbase - Firebird - Oracle - ODBC - Paradox - SQLite - dBASE - MS Access - Zeos

概要

このチュートリアルでは、SQLdb Package に基づいた実用的なコード例を使用してデータベースをプログラミングする方法を示す。 主に初心者を対象としている。データベースと SQL の基本を探している人は、関連する書籍やドキュメントを読む必要がある。 このチュートリアルでは、サンプル データベースemployee.fdbとともにFirebirdを使用する。他のデータベースも使用できる。本文に記載されているように、いくつかの調整を行う必要がある。

このチュートリアルは長く見えるかもしれないが、ほとんどの場合、入力する内容を入力する必要がある理由を説明する大量のテキストだけである。最後に見られるように、アプリケーションを動作させるために必要な実際のコードの量はそれほど多くはない。経験豊富な開発者であれば、説明をざっと読んで、何が起こっているのかをすぐに理解できるだろう。 また、Basic example章の最後で停止して、動作するプログラムを作成することもできる。

このチュートリアルは、Swen による ドイツ語チュートリアル に基づいているが、特に Basic example 以降は拡張されている。Swen はドイツ語版を現状のままにしておきたいと考えている。これが問題となる場合は、このバージョンの名前を変更し、それに基づいて新しいドイツ語訳を作成することができる。

スウェンより: JoostとMichaelに感謝。 彼らの助けがなければ、このチュートリアルはおそらく決して実現しなかっただろう。

必要事項

このチュートリアルは、最近の Lazarus(Laz 1.0) を使い作成されています。; また、より古いバージョンの Lazarus 0.9.30 でも動くだろう。

また、事前に SQLdb_Tutorial0 を読み、サンプルのデータベースを生成のこと。

Basic example

プロジェクトとコンポーネント

TSQLTransaction、および 1 つの TSQLQuery コンポーネントが必要である。

sqldbcomponents.png

TIBConnection は、Interbase/Firebird 固有の接続コンポーネントである。 別のデータベースを使用している場合は、SQLdb tub の適切なコンポーネントを置き換える。 SQLite データベースの場合は 'TSQLite3Connection'、PostgreSQL データベースの場合は TPQConnection。 データベース アクセス ライブラリのセットアップに関する説明は、このチュートリアルの範囲外であるす。そのためにDatabasesを参照のこと。 。

フォーム上の TIBConnection (または同等の接続コンポーネント) をクリックし、オブジェクトインスペクタで名前を DBConnection に変更する。 これにより、別のデータベースを使用する場合のチュートリアルの残りの部分がを簡素にできる。 また、一般に、コンポーネントにプログラム内で役立つ名前 (MainframeDBConnection など) を付けて、それが何を表しているのかわかるようにすることを勧める。

他の2つのコンポーネント TSQLTransaction/jaTSQLQuery/ja は、SQLdb でサポートされるすべてのデータベースに使用できる。

データを表示するには、TDBGrid/ja コンポーネントを使用する。このコンポーネントは、'Data Controls' タブにある。このコンポーネントをデータベースコンポーネントに接続するには、'Data Access tab' の TDataSource コンポーネントが必要である。

これで、最初の例に必要なデータベース コンポーネントがすべて揃った。TDBGrid を拡大して、すべてのデータを表示するのに十分なスペースを確保できる。

コンポーネントをリンクする

次に、コンポーネントを接続する必要があります。 非常に簡単な方法はオブジェクトインスペクタを使用することだが、これをソースコード内で実行することもできる。

DBConnection の Transaction プロパティを 'SQLTransaction1' に変更する。 これにより、SQLTransaction1 の Database プロパティが自動的に 'DBConnection' に変更される。

次に、SQLQuery1 の Database プロパティを 'DBConnection' に変更する。Lazarus は、「トランザクション」プロパティの値を自動的に追加する。

次に、Datasource1 の Dataset プロパティを 'SQLQuery1' に変更する。

最後に、DBGrid1 の Datasource プロパティを 'Datasource1' に変更する。

これで、デフォルトのトランザクションをトランザクション コンポーネントにリンクする接続が完成した。 トランザクションコンポーネントは、そのデータベース プロパティを接続オブジェクトにリンクする。 これら 2 つのコンポーネントは、接続して命令を実行するには十分ですが、クエリを表示するには十分ではない。 このために、データベースを指す(およびそのデフォルトのトランザクションにリンクする) SQLQuery コンポーネントが使用される。SQLQuery を使用して、後でデータを取得し、データベースにポストバックする。

最後に、クエリコンポーネントにリンクされているデータソースコンポーネントは、一種のプレースホルダーです。 クエリデータセット内のどこにいるかを追跡し、GUI コンポーネントがそれにリンクされているため、すべてが同じレコードを表示する。

これが意味不明であっても、絶望しないこと。もう少し作業を加えるだけで、最初のデータを表示できるようになる。

データベースに接続する

データベースのデータを画面に表示するにはどうするか?

まず、DBConnection に、employee.fdb データベースがどこにあるかを伝える必要がある。そのデータベースの場所はオペレーティング システムによって異なる。次のような場所である:

  • .../examples/empbuild/ Linux 上の Firebird インストールのサブディレクトリ
  • Windows マシンの場合は C:\Program Files\Firebird\Firebird_2_5\examples\empbuild\EMPLOYEE.FDB
  • Firebird 埋め込みを使用する場合、ファイルはプロジェクト ディレクトリにある必要がある

ここでも選択が可能だ: オブジェクトインスペクタを使用してパスを割り当てるか、ソースコードで直接行うことができる。

オブジェクトインスペクタを使用することを選択する。DBConnection の「HostName」プロパティを Firebird サーバー名または IP アドレスに設定する。 Firebird サーバーが開発マシンで実行されている場合は、localhost を使用します。 埋め込み Firebird クライアントを使用する場合は、空白の値を使用する。 DBConnection の DatabaseName プロパティを、データベース サーバー上のemployee.fdb ファイルへのパスに変更します。埋め込み Firebird を使用する場合、パス部分は空にし、ファイル名のみを指定する必要がある。

データベースサーバーはデータへのアクセスを許可する前に、ユーザー名とパスワードによる承認をチェックします。本格的なデータベース アプリケーションは、アプリケーションの起動時に両方の値をユーザーに要求し、接続時にこれらをサーバーに送信する。これを行う可能な方法は SQLdb Tutorial3 に示されている。

ただし、今のところ、問題を単純化するために、オブジェクトインスペクタを再度使用してこれらをハードコーディングします。「UserName」プロパティを「SYSDBA」に変更し、「Password」を「masterkey」に変更する(もちろん、データベースのインストールに別のユーザー名/パスワードがある場合は調整のこと)。

ここで、これまでの設定がすべて正しいかどうかを確認する。「Connected」プロパティを「True」に設定します。 データベースのパスが正しくない場合、またはユーザー名またはパスワードが間違っている場合は、エラーメッセージが表示される。接続が成功した場合は、ここで切断する必要があります (「Connected」を「False」に設定する)。

PostgreSQL

PostgreSQL の状況は Firebird の状況と非常に似ている。データベース名にはパスがない。名前の部分 (例: 「employee」) を指定するだけです。 PostgreSQL には埋め込みモードがないため、接続テストを機能させるには「HostName」プロパティを入力する必要がある。

SQLite

SQLite の場合、「HostName」、「UserName」、および「Password」プロパティを空のままにすることができます。 「DatabaseName」を SQLite ファイルの名前に設定します。従業員.sqlite。注: sqlite は、指定されたデータベースが存在しない場合にそれを作成するため、ここでは注意のこと。

次のスクリーンショットのようなものが表示されるはずだ - todo: このスクリーンショットは実際にはさらに進んでおり、現在はボタンだけがある。

Form and components set up

DBGrid のプロパティ「Options」→「dgDisplayMemoText」を「(True)」に変更する。 それ以外の場合は、すべてのデータ フィールドに (MEMO) が表示される。

どのデータを表示するか選択する

Although the connection was successful, no data was displayed. The reason is simple. We haven't told the database server which data to return: the employee.fdb database contains several tables, and we haven't told Firebird the table we want to see. If you don't know the structure of a database, you can use tools like FlameRobin, to display the contents. Lazarus also provides such a tool - the DataDesktop. You can find it in the /tools/lazdatadesktop/ subdirectory of Lazarus. Save our project and then open the project lazdatadesktop.lpi and compile it.

The DataDesktop in action

Back to our example.

We want to display all data from the table 'CUSTOMER'. The SQL instruction for that is:

select * from CUSTOMER

We need to assign this command to the 'SQL' property of SQLQuery1. In the source code of our project this would look like:

SQLQuery1.SQL.Text := 'select * from CUSTOMER';

The SQL instruction must be enclosed by single quotes. You also have the ability to assign the content of another component (e.g. Edit1.Text). This is not always a good idea; see Secure programming (a more advanced text) for details on SQL injection.

Let's add a TButton from the 'Standard' tab on the form. When the user clicks on the button, data retrieval should start. Change its Caption property from "Button1" to Show data".

We will need some code for this. Double click on Button1. Lazarus then creates the skeleton of the necessary procedure. In our source code we should find the following lines:

procedure TForm1.Button1Click(Sender: TObject);
begin

end;

Between begin and end we must enter the instructions needed to display the data.... obviously that will be something to do with SQLQuery1..

The 'SQL' property of SQLQuery1 can only be changed, if SQLQuery1 is not active. That's why we close the component first:

SQLQuery1.Close;

Then we assign our SQL instruction to the 'SQL' property, overwriting any previous SQL commands:

SQLQuery1.SQL.Text := 'select * from CUSTOMER';

Now we need to establish the connection to the database, activate the transaction and open the query:

DBConnection.Connected := True;
SQLTransaction1.Active := True;
SQLQuery1.Open;

You can omit the first two instructions, because they are done automatically by the third instruction. If you compile the project at this point, you could already see the data from the 'CUSTOMER' table.

However, a serious application must make sure that all open database connections are properly closed when not needed anymore. Otherwise the secondary effects would not be foreseeable. So, we use the OnClose event of our form (create it with a double click in the object inspector):

procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin

end;

To close the connection we use the reverse order compared to our opening code:

SQLQuery1.Close;
SQLTransaction1.Active := False;
DBConnection.Connected := False;

If you set DBConnection.Connected to False, the Transaction and the Query is automatically closed and you can omit closing them manually.

要約

Up to now we have learned how to connect to a database using the SQLdb package and how to display the contents of a table on the screen. If you want to add more functionality such as editing, please continue with SQLdb Tutorial2

If you followed the previous steps, then your code should look like:

unit Unit1; 

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, IBConnection, sqldb, db, FileUtil, Forms, Controls,
  Graphics, Dialogs, DBGrids, StdCtrls;

type

  { TForm1 }

  TForm1 = class(TForm)
    Button1: TButton;
    Datasource1: TDatasource;
    DBGrid1: TDBGrid;
    DBConnection: TIBConnection;
    SQLQuery1: TSQLQuery;
    SQLTransaction1: TSQLTransaction;
    procedure Button1Click(Sender: TObject);
    procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
  private
    { private declarations }
  public
    { public declarations }
  end; 

var
  Form1: TForm1; 

implementation

{$R *.lfm}

{ TForm1 }

procedure TForm1.Button1Click(Sender: TObject);
begin
  SQLQuery1.Close;
  SQLQuery1.SQL.Text:= 'select * from CUSTOMER';
  DBConnection.Connected:= True;
  SQLTransaction1.Active:= True;
  SQLQuery1.Open;
end;

procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
  SQLQuery1.Close;
  SQLTransaction1.Active:= False;
  DBConnection.Connected:= False;
end;

end.

関連情報

  • SQLdb Tutorial0/ja: チュートリアルに用いるサンプルの表/データを設定する方法を説明します。
  • SQLdb Tutorial1/ja: DB チュートリアルの第一の部分。データベースのデータを、どのように grid に表示させるかを学びます。
  • SQLdb Tutorial2/ja: DB チュートリアルの第二の部分。データベースのデータの挿入や編集について学びます。
  • SQLdb Tutorial3/ja: DB チュートリアルの第三の部分。複数のデータベースについてのプログラムやログインフォームの使い方を学びます。
  • SQLdb Tutorial4/ja: DB チュートリアルの第四の部分。どのようにデータモジュールを用いるかを学びます。
  • Lazarus Database Overview/ja: Lazarus がサポートしているデータベースについての情報。 データベースごとの記述へのリンクを含みます。
  • SQLdb Package/ja: SQLdb パッケージについての情報
  • SQLdb Programming Reference/ja: SQLdb データベースコンポーネントの入出力の概要
  • SqlDBHowto/ja: SQLdb パッケージを用いることについての情報
  • Working With TSQLQuery/ja: TSQLQuery についての情報