Difference between revisions of "SQLdb Tutorial1/ja"

From Lazarus wiki
Jump to navigationJump to search
(Created page with "{{SQLdb Tutorial1}} {{Infobox databases/ja}} == 導入 == This tutorial shows you how to program databases using practical example code based on the SQLdb Package. It is...")
 
 
(27 intermediate revisions by 3 users not shown)
Line 2: Line 2:
  
 
{{Infobox databases/ja}}
 
{{Infobox databases/ja}}
== 導入 ==
 
  
This tutorial shows you how to program databases using practical example code based on the [[SQLdb Package]]. It is primarily targeted at newbies. If somebody is looking for basics about databases and SQL, he should read relevant books/documentation.
+
== 概要 ==
For this tutorial I use Firebird with the example database employee.fdb. Other databases can also be used; some adjustments will need to be made which are mentioned in the text.
 
  
While this tutorial may seem long, it mostly is just a lot of text that explains why you should type what you type. As you can see at the end, the amount of actual code you will need for a working application is not that great. More experienced developers will hopefully be able to glance through the instructions and quickly understand what's going on.
+
このチュートリアルでは、[[SQLdb Package]] に基づいた実用的なコード例を使用してデータベースをプログラミングする方法を示す。 主に初心者を対象としている。データベースと SQL の基本を探している人は、関連する書籍やドキュメントを読む必要がある。
Also, you can stop at the end of the [[#Basic example|Basic example]] chapter and have a working program.
+
このチュートリアルでは、サンプル データベースemployee.fdbとともにFirebirdを使用する。他のデータベースも使用できる。本文に記載されているように、いくつかの調整を行う必要がある。
  
This tutorial is based on a [[SQLdb Tutorial1/de|German tutorial]] by [[User:Swen|Swen]], but it is extended, especially after the [[#Basic example|Basic example]]. [[User:Swen|Swen]] wants the German version to remain as-is. If this is a problem, we can rename this version and base a new German translation on that.
+
このチュートリアルは長く見えるかもしれないが、ほとんどの場合、入力する内容を入力する必要がある理由を説明する大量のテキストだけである。最後に見られるように、アプリケーションを動作させるために必要な実際のコードの量はそれほど多くはない。経験豊富な開発者であれば、説明をざっと読んで、何が起こっているのかをすぐに理解できるだろう。
 +
また、[[#Basic example|Basic example]]章の最後で停止して、動作するプログラムを作成することもできる。
  
From Swen: thanks to [[User:Loesje|Joost]] and Michael. Without their help this tutorial probably never would have come about.
+
このチュートリアルは、[[User:Swen|Swen]] による [[SQLdb Tutorial1/de|ドイツ語チュートリアル]] に基づいているが、特に [[#Basic example|Basic example]] 以降は拡張されている。[[User:Swen|Swen]] はドイツ語版を現状のままにしておきたいと考えている。これが問題となる場合は、このバージョンの名前を変更し、それに基づいて新しいドイツ語訳を作成することができる。
  
== 要件 ==
+
スウェンより: [[User:Loesje|Joost]]とMichaelに感謝。 彼らの助けがなければ、このチュートリアルはおそらく決して実現しなかっただろう。
  
This tutorial is written for use with recent Lazarus versions (Laz 1.0); it should also work on older versions Lazarus 0.9.30.
+
==必要事項==
  
Please see [[SQLdb_Tutorial0]], which will walk you through making sure you have the right sample database set up.
+
このチュートリアルは、最近の Lazarus(Laz 1.0) を使い作成されています。; また、より古いバージョンの Lazarus 0.9.30 でも動くだろう。
 +
 
 +
また、事前に [[SQLdb_Tutorial0]] を読み、サンプルのデータベースを生成のこと。
  
 
== Basic example ==
 
== Basic example ==
  
 
=== プロジェクトとコンポーネント ===
 
=== プロジェクトとコンポーネント ===
First you should create a new Lazarus project.
+
[[TSQLTransaction]]、および 1 つの [[TSQLQuery]] コンポーネントが必要である。
  
To get access to our database we need one [[TIBConnection]], one [[TSQLTransaction]] and one [[TSQLQuery]] component from the '[[SQLdb tab]]' in the component palette:
+
[[File:sqldbcomponents.png ]]
  
[[File:sqldbcomponents.png‎]]
+
[[TIBConnection]] は、Interbase/Firebird 固有の接続コンポーネントである。
 +
別のデータベースを使用している場合は、[[SQLdb tub]] の適切なコンポーネントを置き換える。 SQLite データベースの場合は '[[TSQLite3Connection]]'、PostgreSQL データベースの場合は [[TPQConnection]]。 データベース アクセス ライブラリのセットアップに関する説明は、このチュートリアルの範囲外であるす。そのために[[Databases]]を参照のこと。 。
  
[[TIBConnection]] is an Interbase/Firebird specific connection component.
+
フォーム上の [[TIBConnection]] (または同等の接続コンポーネント) をクリックし、オブジェクトインスペクタで名前を ''DBConnection'' に変更する。 これにより、別のデータベースを使用する場合のチュートリアルの残りの部分がを簡素にできる。
If you are using a different database, substitute the proper component from the '[[SQLdb tab]], e.g. a [[TSQLite3Connection]]' for an SQLite database, [[TPQConnection]] for a PostgreSQL database. Discussion of setting up any database access libraries is out of scope for this tutorial; see e.g. [[Databases]] for that.
+
また、一般に、コンポーネントにプログラム内で役立つ名前 (MainframeDBConnection など) を付けて、それが何を表しているのかわかるようにすることを勧める。
  
Click on the [[TIBConnection]] (or equivalent connection component) on your form, and in the Object Inspector, change the name to ''DBConnection''. This will simplify the rest of the tutorial when using different databases.
+
他の2つのコンポーネント [[TSQLTransaction/ja]] と [[TSQLQuery/ja]] は、SQLdb でサポートされるすべてのデータベースに使用できる。
It's also generally a good idea to name your components for something useful in your program (e.g. MainframeDBConnection) so you know what it stands for.
 
  
The other two components, [[TSQLTransaction]] and [[TSQLQuery]], can be used for all databases that are supported by SQLdb.
+
データを表示するには、[[TDBGrid/ja]] コンポーネントを使用する。このコンポーネントは、'Data Controls' タブにある。このコンポーネントをデータベースコンポーネントに接続するには、'[[Data Access tab]]' の [[TDataSource]] コンポーネントが必要である。
  
To display the data, we use a [[TDBGrid]] component, which can be found on the 'Data Controls' tab. To connect this component to the database components we need a [[TDataSource]] component from the '[[Data Access tab]]'.
+
これで、最初の例に必要なデータベース コンポーネントがすべて揃った。TDBGrid を拡大して、すべてのデータを表示するのに十分なスペースを確保できる。
  
Now we have all database components needed for the first example. You can enlarge the TDBGrid to have enough space to display all data.
+
=== コンポーネントをリンクする ===
 +
次に、コンポーネントを接続する必要があります。 非常に簡単な方法はオブジェクトインスペクタを使用することだが、これをソースコード内で実行することもできる。
  
=== Link the components ===
+
DBConnection の ''Transaction'' プロパティを 'SQLTransaction1' に変更する。 これにより、SQLTransaction1 の ''Database'' プロパティが自動的に 'DBConnection' に変更される。
Next we need to connect our components. A very simple way is to use the object inspector, but you can also do this in your source code.
 
  
Change the ''Transaction'' property of DBConnection to 'SQLTransaction1'. This causes the ''Database'' property of SQLTransaction1 to automatically change to 'DBConnection'.
+
次に、SQLQuery1 の ''Database'' プロパティを 'DBConnection' に変更する。Lazarus は、「トランザクション」プロパティの値を自動的に追加する。
  
Then, change the ''Database'' property of SQLQuery1 to 'DBConnection'. Lazarus automatically adds the value for the 'Transaction' property.
+
次に、Datasource1 の ''Dataset'' プロパティを 'SQLQuery1' に変更する。
  
Next, change the ''Dataset'' property of Datasource1 to 'SQLQuery1'.
+
最後に、DBGrid1 の ''Datasource'' プロパティを 'Datasource1' に変更する。
  
Finally we change the ''Datasource'' property of DBGrid1 to 'Datasource1'.
+
これで、デフォルトのトランザクションをトランザクション コンポーネントにリンクする接続が完成した。 トランザクションコンポーネントは、そのデータベース プロパティを接続オブジェクトにリンクする。 これら 2 つのコンポーネントは、接続して命令を実行するには十分ですが、クエリを表示するには十分ではない。 このために、データベースを指す(およびそのデフォルトのトランザクションにリンクする) SQLQuery コンポーネントが使用される。SQLQuery を使用して、後でデータを取得し、データベースにポストバックする。
  
We now end up with a connection that links its default transaction to a transaction component. The transaction component links its database property to the connection object. These two components are enough to connect and execute instructions, but not enough to show queries. For this, an SQLQuery component is used, which points to the database (and links to its default transaction). With the SQLQuery, we'll later on retrieve data and post it back to the database.
+
最後に、クエリコンポーネントにリンクされているデータソースコンポーネントは、一種のプレースホルダーです。 クエリデータセット内のどこにいるかを追跡し、GUI コンポーネントがそれにリンクされているため、すべてが同じレコードを表示する。
  
Finally, the datasource component, which is linked to the query component, is a sort of place holder. It keeps track of where in the query dataset we are and the GUI components are linked to that so they all show the same record.
+
これが意味不明であっても、絶望しないこと。もう少し作業を加えるだけで、最初のデータを表示できるようになる。
  
If this is gibberish to you, don't despair: with just some more work, we'll be able to show our first data.
+
=== データベースに接続する ===
 +
データベースのデータを画面に表示するにはどうするか?
  
=== Connecting to the database ===
+
まず、DBConnection に、employee.fdb データベースがどこにあるかを伝える必要がある。そのデータベースの場所はオペレーティング システムによって異なる。次のような場所である:
How can we now show the data from our database on the screen?
+
* .../examples/empbuild/ Linux 上の Firebird インストールのサブディレクトリ
 +
* Windows マシンの場合は C:\Program Files\Firebird\Firebird_2_5\examples\empbuild\EMPLOYEE.FDB
 +
* Firebird 埋め込みを使用する場合、ファイルはプロジェクト ディレクトリにある必要がある
  
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:
+
ここでも選択が可能だ: オブジェクトインスペクタを使用してパスを割り当てるか、ソースコードで直接行うことができる。
* .../examples/empbuild/ subdirectory of your Firebird installation on Linux
 
* C:\Program Files\Firebird\Firebird_2_5\examples\empbuild\EMPLOYEE.FDB on a Windows machine
 
* Using Firebird embedded, the file should be in your project directory
 
  
Again you have the choice: you can use the object inspector to assign the path or do it directly in your source code.
+
オブジェクトインスペクタを使用することを選択する。DBConnection の「HostName」プロパティを Firebird サーバ名または IP アドレスに設定する。 Firebird サーバが開発マシンで実行されている場合は、localhost を使用します。 埋め込み Firebird クライアントを使用する場合は、空白の値を使用する。
 +
DBConnection の ''DatabaseName'' プロパティを、データベース サーバ上のemployee.fdb ファイルへのパスに変更します。埋め込み Firebird を使用する場合、パス部分は空にし、ファイル名のみを指定する必要がある。
  
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.
+
データベースサーバはデータへのアクセスを許可する前に、ユーザー名とパスワードによる承認をチェックします。本格的なデータベース アプリケーションは、アプリケーションの起動時に両方の値をユーザーに要求し、接続時にこれらをサーバに送信する。これを行う可能な方法は [[SQLdb Tutorial3]] に示されている。
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.
 
  
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]].
+
ただし、今のところ、問題を単純化するために、オブジェクトインスペクタを再度使用してこれらをハードコーディングします。「UserName」プロパティを「SYSDBA」に変更し、「Password」を「masterkey」に変更する(もちろん、データベースのインストールに別のユーザー名/パスワードがある場合は調整のこと)。
  
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).
+
ここで、これまでの設定がすべて正しいかどうかを確認する。「Connected」プロパティを「True」に設定します。 データベースのパスが正しくない場合、またはユーザー名またはパスワードが間違っている場合は、エラーメッセージが表示される。接続が成功した場合は、ここで切断する必要があります (「Connected」を「False」に設定する)
 
 
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').
 
  
 
==== 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]]
  
=== Choosing what data to show ===
+
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 [http://www.flamerobin.org/index.php 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.
 
  
[[Image:DataDictonary1.png|framed|center|The DataDesktop in action]]
+
=== 表示するデータの選択 ===
 +
接続は成功したが、データが表示されなかった。 理由は簡単である。 どのデータを返すかをデータベース サーバに伝えていない。employee.fdb データベースにはいくつかのテーブルが含まれており、確認したいテーブルを Firebird に伝えていない。 データベースの構造がわからない場合は、[http://www.flamerobin.org/index.php FlameRobin] などのツールを使用して内容を表示できます。 Lazarus はそのようなツール、[[DataDesktop]] も提供する。 これは、Lazarus の /tools/lazdatadesktop/ サブディレクトリにある。 プロジェクトを保存し、プロジェクト lazdatadesktop.lpi を開いてコンパイルする。
  
Back to our example.  
+
[[Image:DataDictonary1.png|framed|center|DataDesktopが起動したときの模様]]
  
We want to display all data from the table 'CUSTOMER'. The SQL instruction for that is:
+
例に戻る。
 +
 
 +
テーブル「CUSTOMER」のすべてのデータを表示したいと考えている。 そのための SQL 命令は次のとおりである。
 
<syntaxhighlight lang="sql">
 
<syntaxhighlight lang="sql">
 
select * from CUSTOMER
 
select * from CUSTOMER
</syntaxhighlight>  
+
</syntaxhighlight>
  
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' プロパティに割り当てる必要がある。 私たちのプロジェクトのソースコードでは、これは次のようになる。
<syntaxhighlight>
+
 
 +
<syntaxhighlight lang=pascal>
 
SQLQuery1.SQL.Text := 'select * from CUSTOMER';
 
SQLQuery1.SQL.Text := 'select * from CUSTOMER';
 
</syntaxhighlight>
 
</syntaxhighlight>
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".
+
SQL 命令は一重引用符で囲む必要がある。 別のコンポーネント (Edit1.Text など) のコンテンツを割り当てることもできる。 これは必ずしも良い考えとは限らない。 SQL インジェクションの詳細については、[[Secure programming]] (より高度なテキスト) を参照のこと。
  
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:
+
フォームの「標準」タブから「TButton」を追加する。 ユーザーがボタンをクリックすると、データの取得が開始される。 ''Caption'' プロパティを「Button1」から「Show data」に変更する。
  
<syntaxhighlight>
+
これにはコードが必要になる。 Button1 をダブルクリックする。 次に、Lazarusは必要な手順の骨格を作成する。 ソースコードには次の行があるはずだ。
procedure TForm1.Button1Click(Sender: TObject);
+
 
 +
<syntaxhighlight lang=pascal>
 +
プロシージャ TForm1.Button1Click(Sender: TObject);
 
begin
 
begin
  
end;            
+
end;
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Between ''begin'' and ''end'' we must enter the instructions needed to display the data.... obviously that will be something to do with SQLQuery1..
+
「begin」と「end」の間に、データを表示するために必要な命令を入力する必要がある。明らかに、これは SQLQuery1 と関係がある。
  
The 'SQL' property of SQLQuery1 can only be changed, if SQLQuery1 is not active. That's why we close the component first:
+
SQLQuery1 の 'SQL' プロパティは、SQLQuery1 がアクティブでない場合にのみ変更できる。 そのため、最初にコンポーネントを閉じる。
<syntaxhighlight>
+
 
 +
<syntaxhighlight lang=pascal>
 
SQLQuery1.Close;
 
SQLQuery1.Close;
 
</syntaxhighlight>
 
</syntaxhighlight>
Then we assign our SQL instruction to the 'SQL' property, overwriting any previous SQL commands:
+
 
<syntaxhighlight>
+
次に、SQL 命令を「SQL」プロパティに割り当て、以前の SQL コマンドを上書きする。
 +
 
 +
<syntaxhighlight lang=pascal>
 
SQLQuery1.SQL.Text := 'select * from CUSTOMER';
 
SQLQuery1.SQL.Text := 'select * from CUSTOMER';
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Now we need to establish the connection to the database, activate the transaction and open the query:
+
次に、データベースへの接続を確立し、トランザクションをアクティブにしてクエリを開く必要がある。
<syntaxhighlight>
+
 
 +
<syntaxhighlight lang=pascal>
 
DBConnection.Connected := True;
 
DBConnection.Connected := True;
 
SQLTransaction1.Active := True;
 
SQLTransaction1.Active := True;
 
SQLQuery1.Open;
 
SQLQuery1.Open;
 
</syntaxhighlight>
 
</syntaxhighlight>
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.
+
最初の 2 つの命令は 3 番目の命令によって自動的に実行されるため、省略できる。 この時点でプロジェクトをコンパイルすると、CUSTOMER」テーブルのデータがすでに表示されているはずだ。
  
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):
+
ただし、本格的なアプリケーションでは、開いているすべてのデータベース接続が不要になったときに適切に閉じられるようにする必要がある。 そうでなければ、二次的な影響は予測できない。そこで、フォームの OnClose イベントを使用します (オブジェクトインスペクタでダブルクリックして作成する)
  
<syntaxhighlight>
+
<syntaxhighlight lang=pascal>
procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
+
プロシージャ TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
 
begin
 
begin
  
end;            
+
end;
 
</syntaxhighlight>
 
</syntaxhighlight>
  
To close the connection we use the reverse order compared to our opening code:
+
接続を閉じるには、開始コードとは逆の順序を使用する。
<syntaxhighlight>
+
 
 +
<syntaxhighlight lang=pascal>
 
SQLQuery1.Close;
 
SQLQuery1.Close;
 
SQLTransaction1.Active := False;
 
SQLTransaction1.Active := False;
Line 150: Line 158:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
If you set DBConnection.Connected to False, the Transaction and the Query is automatically closed and you can omit closing them manually.
+
DBConnection.Connected False に設定すると、トランザクションとクエリは自動的に閉じられるため、手動で閉じる必要はない。
  
== Summary ==
+
== 要約 ==
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.
+
ここまで、SQLdb パッケージを使用してデータベースに接続する方法と、テーブルの内容を画面に表示する方法を学習した。 編集などの機能をさらに追加したい場合は、SQLdb チュートリアル 2 に進まれたい。
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:
+
前の手順に従った場合、コードは次のようになる:
<syntaxhighlight>
+
<syntaxhighlight lang=pascal>
 
unit Unit1;  
 
unit Unit1;  
  
Line 214: Line 221:
 
end.                                                 
 
end.                                                 
 
</syntaxhighlight>
 
</syntaxhighlight>
 
  
 
== 関連情報 ==
 
== 関連情報 ==
Line 227: Line 233:
 
* [[SqlDBHowto/ja]]: SQLdb パッケージを用いることについての情報
 
* [[SqlDBHowto/ja]]: SQLdb パッケージを用いることについての情報
 
* [[Working With TSQLQuery/ja]]: TSQLQuery についての情報
 
* [[Working With TSQLQuery/ja]]: TSQLQuery についての情報
 
[[Category:Databases/ja]]
 
[[Category:Tutorials/ja]]
 
[[Category:Lazarus/ja]]
 

Latest revision as of 21:33, 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) が表示される。

表示するデータの選択

接続は成功したが、データが表示されなかった。 理由は簡単である。 どのデータを返すかをデータベース サーバに伝えていない。employee.fdb データベースにはいくつかのテーブルが含まれており、確認したいテーブルを Firebird に伝えていない。 データベースの構造がわからない場合は、FlameRobin などのツールを使用して内容を表示できます。 Lazarus はそのようなツール、DataDesktop も提供する。 これは、Lazarus の /tools/lazdatadesktop/ サブディレクトリにある。 プロジェクトを保存し、プロジェクト lazdatadesktop.lpi を開いてコンパイルする。

DataDesktopが起動したときの模様

例に戻る。

テーブル「CUSTOMER」のすべてのデータを表示したいと考えている。 そのための SQL 命令は次のとおりである。

select * from CUSTOMER

このコマンドを SQLQuery1 の 'SQL' プロパティに割り当てる必要がある。 私たちのプロジェクトのソースコードでは、これは次のようになる。

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

SQL 命令は一重引用符で囲む必要がある。 別のコンポーネント (Edit1.Text など) のコンテンツを割り当てることもできる。 これは必ずしも良い考えとは限らない。 SQL インジェクションの詳細については、Secure programming (より高度なテキスト) を参照のこと。

フォームの「標準」タブから「TButton」を追加する。 ユーザーがボタンをクリックすると、データの取得が開始される。 Caption プロパティを「Button1」から「Show data」に変更する。

これにはコードが必要になる。 Button1 をダブルクリックする。 次に、Lazarusは必要な手順の骨格を作成する。 ソースコードには次の行があるはずだ。

プロシージャ TForm1.Button1Click(Sender: TObject);
begin

end;

「begin」と「end」の間に、データを表示するために必要な命令を入力する必要がある。明らかに、これは SQLQuery1 と関係がある。

SQLQuery1 の 'SQL' プロパティは、SQLQuery1 がアクティブでない場合にのみ変更できる。 そのため、最初にコンポーネントを閉じる。

SQLQuery1.Close;

次に、SQL 命令を「SQL」プロパティに割り当て、以前の SQL コマンドを上書きする。

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

次に、データベースへの接続を確立し、トランザクションをアクティブにしてクエリを開く必要がある。

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

最初の 2 つの命令は 3 番目の命令によって自動的に実行されるため、省略できる。 この時点でプロジェクトをコンパイルすると、CUSTOMER」テーブルのデータがすでに表示されているはずだ。

ただし、本格的なアプリケーションでは、開いているすべてのデータベース接続が不要になったときに適切に閉じられるようにする必要がある。 そうでなければ、二次的な影響は予測できない。そこで、フォームの OnClose イベントを使用します (オブジェクトインスペクタでダブルクリックして作成する)。

プロシージャ TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin

end;

接続を閉じるには、開始コードとは逆の順序を使用する。

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

DBConnection.Connected を False に設定すると、トランザクションとクエリは自動的に閉じられるため、手動で閉じる必要はない。

要約

ここまで、SQLdb パッケージを使用してデータベースに接続する方法と、テーブルの内容を画面に表示する方法を学習した。 編集などの機能をさらに追加したい場合は、SQLdb チュートリアル 2 に進まれたい。

前の手順に従った場合、コードは次のようになる:

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 についての情報