Difference between revisions of "MySQLDatabases/ja"

From Lazarus wiki
Jump to navigationJump to search
 
 
(26 intermediate revisions by 2 users not shown)
Line 1: Line 1:
 
{{MySQLDatabases}}
 
{{MySQLDatabases}}
 +
 +
{{Japanese Menu}}
  
 
'''Work in progress'''
 
'''Work in progress'''
Line 7: Line 9:
 
In the [[Lazarus Database Tutorial#Lazarus and MySQL|Database tutorial]]のページで、MySQLサーバーへの最初の接続を試してみる実例があります。  
 
In the [[Lazarus Database Tutorial#Lazarus and MySQL|Database tutorial]]のページで、MySQLサーバーへの最初の接続を試してみる実例があります。  
 
そのときには、ビジュアル、ノンビジュアルの、どんなコンポーネントも使いませんでした。このページでは、(多分)もっと簡単な方法で、MySQLサーバーに接続する方法を紹介します。
 
そのときには、ビジュアル、ノンビジュアルの、どんなコンポーネントも使いませんでした。このページでは、(多分)もっと簡単な方法で、MySQLサーバーに接続する方法を紹介します。
==利用するコンポーネント ==
+
== 利用するコンポーネント ==
  
===MySQL Components===
+
=== SQLdb Components ===
If you look in the $Lazarus/components/mysql directory you will find two lazarus packages. There is a package for MySQL version 3.2x (mysql3laz.lpk) and one for MySQL version 4.x (mysql4laz.lpk). If you did not do so yet, install the appropriate package, depending on the server version. Remember that it is not possible to use the package for version 3 to connect to a server running version 4 or vice versa.
 
When you've installed this package you will see a new tab in the component palet, called MySQL. On this tab there are two components, TMySQLDatabase and TMySQLDataset.
 
  
NB. Before trying to install this components in Lazarus be sure that you have appropiated MySQL client libraries or else Lazarus may not start after install.
+
$Lazarus/components/sqldbディレクトリに、もうひとつ別のパッケージがあります。
===SQLdb Components===
+
このディレクトリに、sqldblaz.lpkがあります。このパッケージと、Lazarus/components/sqldb/mysql directoryから、mysql4connlaz.lpkをインストールする必要があります。
Another possibility is the installation of the package in the $Lazarus/components/sqldb directory. In this directory you see a package file called sqldblaz.lpk. You need to install this package and the mysql4connlaz.lpk from the $Lazarus/components/sqldb/mysql directory. The first package contains some general components used for all databases. These component are TSQLTransaction and TSQLQuery and can be found on the new SQLdb tab. After installation of the mysql4connlaz.lpk you will find a third component on the SQLdb tab called TMySQLConnection (depicted by a dolphin).
+
最初のsqldblaz.lpkは、すべてのデータベースで利用する一般的なコンポーネントを含みます。これらのコンポーネントは、SQLdbタブの中の、TSQLTransactionやTSQLQueryです。mysql4connlaz.lpkをインストールした後では、SQLdbタブにTMySQLConnectionを見つけることができるでしょう。(depicted by a dolphin)
  
If you can't find the $Lazarus/components/sqldb/mysql directory and mysql4connlaz.lpk, then this means that you are using a newer version in which mysql4connlaz.lpk merged with sqldblaz.lpk. It is OK, if you instal sqldblaz.lpk, you will get all components mentioned in the same Lazarus IDE toolbar TAB.
+
もし、$Lazarus/components/sqldb/mysql ディレクトリや、 mysql4connlaz.lpkを見つけられない場合、mysql4connlaz.lpkがsqldblaz.lpkにマージされた新しいバージョンを使っている事を意味しています。
 +
もしそうだったら、sqldblaz.lpkをインストールすれば、すべてのコンポーネントをLazarusのIDEのツールバーの中に手に入れることができます。
  
If you do not know how to install components / packages, have a look at this [[Install Packages|page]] for an "Install Howto".
+
もし、どうやってコンポーネントやパッケージをインストールするか分からなかったら、[[Install Packages/ja|インストールの方法の解説]]を呼んでください。
As the SQLdb components are the more general and can be used for other databases just by replacing the TMySQLConnection with for instance a TIBConnection, we will develop a program with the SQLdb components.
+
SQLdbコンポーネントはより一般的で、他のデータベースにも接続できるので、たとえば、TMySQLConnectionをTIBConnectionへ置き換えることも可能です。ですから、(より一般的な)SQLdbコンポーネントでプログラムを開発するようにしましょう。
  
==Explanation of the used components==
+
==利用したコンポーネントの説明==
 
===TMySQLConnection===
 
===TMySQLConnection===
  
The TMySQLConnection is used to store parameters to connect to the database server. It enables you to set the host to connect to and the userid and password to use in the connection. Another property of the TMySQLConnection is used to indicate the database you want to use. The 'LoginPrompt' is not functional yet, so make sure that next to the HostName and DatabaseName the UserName and Password properties have values as well before you try to open the connection.
+
TMySQLConnectionは、データベースサーバーに接続するパラメータを保存するのに使われます。
Be sure to use a TSQLTransaction as well and connect it to your MySQLConnection by setting the Transaction property, or you will not be able to open a SQLQuery.
+
接続するのに使われる、接続するホスト、ユーザーID,パスワードをセットします。
 +
TMySQLConnectionのほかのプロパティは、使いたい時に必要に応じて使います。
  
Note. In latest SVN version of Lazarus you will find 3 MySQLConnection components. These are TMySQL40Connection, TMySQL41Connection and TMySQL50Connection. Make sure you use the correct one to connect to your server.
+
'LoginPrompt'プロパティは、まだ機能しないので、接続を開始するために必要なHostNameとDatabaseName、UserName、Passwordプロパティは必ず設定してください。
So if you are running MySQL 4.1 use the TMySQL41Connection.
+
 
 +
TSQLTransactionを使う場合、MySQLConnectionと同様に、Transactionプロパティを設定してください。さもないと、SQLQueryをオープンすることができません。
 +
 
 +
 
 +
ノート:最新のLazarusのSVN版では、MySQLConnectionコンポーネントに3つのバージョンがあります。
 +
それらは、TMySQL40Connection, TMySQL41Connection and TMySQL50Connectionです。
 +
 
 +
サーバーにあっている正しいものを使うようにしてください。もし、MySQL 4.1を使っているなら、TMySQL41Connectionを使ってください。
  
 
===TSQLTransaction===
 
===TSQLTransaction===
A SQLTransaction is needed for some internal housekeeping. A SQLTransaction is automatically activated when you open a dataset using it. Closing a connection also deactivates the related transaction and closes all datasets using it.
+
 
 +
SQLTransactionは、内部的な仕事に使われます。SQLTransactionは、あなたがデータセットをオープンするときには、自動的にactivateされます。接続を閉じるときには、関連のあるトランザクションもdeactivateされ、SQLTransactionをつかっているデータセットもcloseされます。
  
 
===TSQLQuery===
 
===TSQLQuery===
TSQLQuery is used to execute SQLstatements on the server. You can retrieve data by setting the SQL to some SELECT statement and call the Open method. Or you can manipulate data by issuing some an INSERT, DELETE or UPDATE statement. In the latter case you should not use the Open method but the ExecSQL method.
+
 
 +
TSQLQueryはSQL文を実行するときに使用されます。SQLにSELECT文を設定し、Openメソッドをコールすることで、データを受け取ることができます。または、INSERT,DELETE,UPDATE文で、データを操作することができます。この場合は、Openメソッドではなく、ExecSQLメソッドを使います。
  
 
===TDataSource===
 
===TDataSource===
  
A datasource provides the connection between the visible data aware components like DBEdit, DBGrid and a dataset. It makes the data available for the data aware components to display.
+
データソースは、DBEditやDBGridといった目に見える「データを表示し操作するコンポーネント(=data aware components)」と、データセットの間の接続を提供します。データソースは、data aware componentに表示するためのデータを提供する役割があります。
A datasource can only be connected to a single dataset at a time but there can be several data aware components connected.
+
 
 +
データソースは、1度に1つのデータセットに接続されるべきです。しかし、いくつかのdata awareコンポーネントに接続されることがあります。
  
 
===TDBGrid===
 
===TDBGrid===
A DBGrid can be used to present the data retrieved by a Dataset. The DBGrid needs a datasource to connect to a dataset. When the dataset is opened, the DBgrid will automatically be populated with the data.
+
DBグリッドはデータセットのデータを表示するのに使われます。DBGridはデータセットに接続するために、データソースを必要とします。データセットがOpenされると、DBグリッドは自動的にデータを表示します。
 +
 
 +
==私達のプログラム==
 +
 
 +
===私達がベースとするもの===
 +
私達は、[[Lazarus Database Tutorial|ここ]]で作られたものをベースにしたプログラムをつくるようにしましょう。
 +
これは、[[Lazarus Database Tutorial#Connecting to MySQL from a Lazarus Application|オリジナル (in English)]]  [[user:Kirkpatc|Chris]]によるものをベースにしています。
  
==Our program==
+
===メインフォーム===
  
===The basics===
+
私たちは、同じメイン画面を使用し、最初から、すべての機能性を築き上げます。 コンポーネントが本当にすべての面倒なことを取り去ってくれますが、これから、気をつけるべきいろいろな事があります。
We will try to make a program based on the one made [[Lazarus Database Tutorial/nl#Verbinding met MySQL vanuit een Lazarus Programma|here (in Dutch)]] which is based on the [[Lazarus Database Tutorial#Connecting to MySQL from a Lazarus Application|original (in English)]] by [[user:kirkpatc|Chris]].
+
 
 +
それでは、次のような画面を作るところから始めてみましょう。<br> [[image:Trymysql.png]]<br>
 +
SQLdbタブから、TMySQLConnection、TSQLTransaction,TSQLQuery
 +
[[image:Components.png]]をフォームの上におきます。Connectionコンポーネント以外は、これらのコンポーネントにつけられたデフォルトの名前を変更しないでください。
 +
すべてのバージョンのMySQLに対応するために、MySQL??Connectionには、MySQLConnection1という名前をつけてください。そして、これらのコンポーネントが連携して動作するために、リンクする必要がありますので、次のようにプロパティをセットしてください。
  
===The main form===
 
We will use the same main screen and build all functionality from scratch :) As you will see there is a lot less to take care of, because the components really take away all the hard stuff! So lets start by making a screen that looks like this.<br> [[image:Trymysql.png]]<br>
 
From the SQLdb-tab place a TMySQLConnection, a TSQLTransaction and a TSQLQuery [[image:Components.png]] on this form. Don't change the default names given to this components. Except for the Connection component. To make this article the same for all versions of MySQL, name your MySQL??Connection component: MySQLConnection1
 
We have to link these components together so they can do their job. So the following properties have to be set:
 
 
{|
 
{|
 
|-
 
|-
| '''Component''' || '''Property''' || '''Value'''
+
| '''コンポーネント''' || '''プロパティ''' || ''''''
 
|-
 
|-
 
| MySQLConnection1 || Transaction || SQLTransaction1
 
| MySQLConnection1 || Transaction || SQLTransaction1
Line 66: Line 84:
 
| SQLQuery1 || Transaction || SQLTransaction1
 
| SQLQuery1 || Transaction || SQLTransaction1
 
|}
 
|}
The Transaction-property of SQLQuery1 will automatically be set if you have set the Transaction property of MySQLConnection1 first. When you set this, you will notice that SQLTransaction1.Database has been set to MySQLConnection1.
 
  
As said earlier: Make sure you are using the correct Connection component for your version of MySQL server.
+
SQLQuery1のトランザクションのプロパティは、最初にMySQLConnection1のトランザクションプロパティをセットしたときに、自動的に設定されます。
  
===The code===
+
これを設定したら、SQLTransaction1.Databaseに、MySQLConnection1が設定されていることに注意してください。
  
As you can see in the screen dump the only buttons available on start of the program are "Connect to server" and "Exit". For the other buttons to work we need more information so these are disabled. We could decide to disable "Connect to Server" as well until the information for the host, username and password has been given. I decided against this because our user might think: "Nothing seems possible, so let's hit exit." :)
+
前にも言いましたが、MySQLサーバーのバージョンにあった正しい接続コンポーネントを使っていることを確認してください。
  
Before I start giving you any code I would like to stress that there should be more exception handling in the code. Critical sections should be placed in
+
===プログラムコード===
 +
 
 +
スクリーン画像を見てください。プログラムの開始時に有効なボタンは、"Connect to Server"と"Exit"だけです。
 +
その他のボタンが機能するためには、まだ充分な情報がないので、無効になっています。
 +
"Connect to Server"ボタンも、接続先ホスト、ユーザー名、パスワードが与えられるまでは無効にしておく、ということもできますが、この場合、ユーザーは何もすることが無いから、"Exit"を押すしかないな、と考えてしまうでしょう。
 +
 
 +
まずコードを示す前に、コードには、例外を扱うコードを入れるべきであることを強調したいと思います。
 +
 
 +
クリティカルなセクションは、
 
  try ... finally
 
  try ... finally
or
+
あるいは、
 
  try ... except
 
  try ... except
constructions.
+
の構文に入れるようにしてください。
 +
 
 +
====サーバーに接続する====
 +
最初にやることは、サーバーに接続することです。接続する時に、サーバーのどのデータベースが利用可能かどうか知らなければ、実行時の接続するときにデータベースのリストから尋ねるようにできます。
 +
しかしながら、今回は1つを選択し、MySQLConnectionのプロパティの、有効なDatabaseNameを開いて接続するようにしてください。コードの中に、私が使っている"mysql"データベースがあります。
 +
このデータベースはmysqlによって内部的に使われるもので、常に存在します。
  
====Connect to a server====
 
The first thing we have to do is get connected to our server. As when connecting we don't know what databases are available on the server we will ask for a list of databases on connecting. However there is one catch, to make the connection we have to enter a valid DatabaseName in the properties of the MySQLConnection. You will see in the code that I am using the "mysql" database. This database is used by mysql for some housekeeping so it will always be there.
 
 
  procedure TFormTryMySQL.ConnectButtonClick(Sender: TObject);
 
  procedure TFormTryMySQL.ConnectButtonClick(Sender: TObject);
 
  begin
 
  begin
Line 108: Line 136:
 
  end;
 
  end;
  
The first thing we do is check to see if we are connected to a server, if we are then we call a private method "CloseConnection". In this method some more housekeeping is done. like disabling buttons and clearing comboboxes and listboxes. Then we set the necessary parameters to connect to server.
+
まず、最初にチェックすることは、サーバーに接続しているかどうか、そして、プライベートメソッドのCloseConnectionを呼んでいるか、ということです。このメソッドで、いくつかの内部的な処理がおこなわれ、終了します。ボタンをdisableにしたり、チェックボックスやリストボックスをクリアしたりします。
:''Throughout our program you may see calls to ShowString. This method adds a line to the memo on our form which acts like a kind of log.''
+
そして、サーバに接続するために必要なパラメータをセットします。
With the parameters set, we can connect to the server. This is done by calling
+
 
 +
:''プログラムでは、ShowStringをコールしていることに気が付くでしょう。これは、memoにログのように、文を追加していきます。''
 +
 
 +
パラメータをセットすれば、サーバーに接続できます。これは、次の文をコールすることで実行されます。
 +
 
 
  MySQLConnection1.Open;
 
  MySQLConnection1.Open;
In a proper application one would place this in an exception handling construct to present a friendly message to the user if the connection failed.
+
 
When we are connected we want to get a list of databases from the server. To get data from the server a TSQLQuery is used. The SQL property is used to store the SQL-statement send to the server. MySQL knows the "SHOW DATABASES" command to get the list of databases. So after we have set the SQL-text, we call
+
行儀の良いアプリケーションでは、これを例外処理構造にいれて、接続が失敗した場合に、わかりやすいメッセージでユーザーに伝えるべきです。
 +
 
 +
接続がおこなわれれば、サーバーからデータベースのリストを取得します。サーバーからデータを取得するには、TSQLQueryを使います。SQLプロパティに、SQL文を入れ、サーバーに送ります。MySQLサーバーは、"SHOW DATABASES"コマンドが、データベースのリストを取得するコマンドである、ということを理解します。SQL文をセットしたら、次のようにコールします。
 +
 
 
  SQLQuery1.Open;
 
  SQLQuery1.Open;
The result set of a SQLQuery can be examined through the fields property. As you can see we iterate through the records by calling
+
 
 +
SQLQueryの結果セットは、fieldsプロパティを使って調べることができます。
 +
レコードをイテレーションするために、次のようにコールします。
 +
 
 
  SQLQuery1.Next;
 
  SQLQuery1.Next;
When we have added all available databases to our combobox, we close the SQLQuery again.
 
  
====Selecting a database====
+
すべての利用できるデータベースをコンボボックスに追加したら、SQLQueryを再びクローズしてください。
If the user selects a database in the DatabaseComboBox we enable the "Select Database" button. In the OnClick event of this button we set the DatabaseName of MySQLConnection1, and request a list of tables. The last statement of this procedure enables the "Open Query" Button, so the user can enter a query in the "Command" Editbox and have it send to the server.
+
 
 +
====データベースを選択する====
 +
ユーザがDatabaseComboBoxからデータベースを選択したときに、"Select Database"ボタンを有効にします。そのボタンのOnClickイベントで、MySQLConnection1のDatabaseNameをセットして、テーブルのリストを要求します。このプロシージャの最後の命令で、"Open Query"ボタンを有効にして、ユーザーが"Command"エディットボックスでクエリを入力でき、サーバに送信できるようにします。
 +
 
 
  procedure TFormTryMySQL.SelectDBButtonClick(Sender: TObject);
 
  procedure TFormTryMySQL.SelectDBButtonClick(Sender: TObject);
 
  begin
 
  begin
Line 140: Line 180:
 
   OpenQueryButton.Enabled := True;
 
   OpenQueryButton.Enabled := True;
 
  end;
 
  end;
MySQL has a special command to get a list of tables, comparable to getting the list of databases, "show tables". The result of this query is handled in the same way as the list of databases and all the tables are added to the TableComboBox.
 
You might wonder why we do not open the connection again before opening the query? Well, this is done automatically (if necessary) when we activate the SQLQuery.
 
  
====Fields in a table====
+
MySQLはデータベースのリストを取得する場合と比較して、テーブルのリストを取得するための特別のコマンド"show tables"を持っています。このクエリの結果もデータベースリストと同じように、すべてのテーブルをTableComboBoxに追加していきます。
In MySQL you can again use a form of "SHOW" to get the fields in a table. In this case "SHOW COLUMNS FROM <tablename>". If the user picks a table from the TableComboBox the OnChangeEvent of this ComboBox is triggered which fills the FieldListbox.
+
 
 +
どうしてこのクエリをオープンする前に、コネクションを再度オープンしなかったのか、疑問に思うかもしれません。
 +
これは、自動的にSQLQueryが有効になったときに、必要に応じて内部的におこなわれるので、必ずしも必要ではありません。
 +
 
 +
====テーブル内のフィールド====
 +
MySQLにおいて、テーブルと同様に、テーブルのフィールドを取得する場合にも、"SHOW"を使って、"SHOW COLUMNS FROM <tablename>"とすることでできます。ユーザーがテーブルをTableComboBoxから選択すると、そのComboBoxのOnChangedEventがトリガーとなって、FieldListboxへフィールドの名前を入れます。
 +
 
 
  procedure TFormTryMySQL.TableComboBoxChange(Sender: TObject);
 
  procedure TFormTryMySQL.TableComboBoxChange(Sender: TObject);
 
  begin
 
  begin
Line 156: Line 200:
 
   SQLQuery1.Close;
 
   SQLQuery1.Close;
 
  end;
 
  end;
As well as the names of the fields, the result set contains information on the type of field, if the field is a key, if nulls are allowed and some more.
 
  
====Showing the data====
+
結果セットには、フィールドの名前と同じように、フィールドの型情報、キーになっているかどうか、nullが許されるか、など、色んな情報が含まれています。
Well as we said we would use components to get connected to the database, lets use some components to show the data as well. We will use a second form to show a grid with the data requested by the user. This form will be shown when the user typed a SQL command in the "Command" editbox and afterwards clicks the "Open Query" button. This is the OnClick event:
+
 
 +
====データを表示する====
 +
データベースに接続するために、コンポーネントを使うという方針と同様に、データを表示するためにも、いくつかのコンポーネントを使ってみましょう。
 +
 
 +
ユーザーからの要求に応じてデータを表示するグリッドのために、2番目のフォームを使います。
 +
このフォームは、ユーザーが"Command"エディットボックスにSQLコマンドを入力し、"Open Query"ボタンを押した後で表示されるようにします。
 +
 
 +
これはそのOnClickイベントです。
 +
 
 
  procedure TFormTryMySQL.OpenQueryButtonClick(Sender: TObject);
 
  procedure TFormTryMySQL.OpenQueryButtonClick(Sender: TObject);
 
  begin
 
  begin
Line 170: Line 221:
 
   SQLQuery1.Close;
 
   SQLQuery1.Close;
 
  end;
 
  end;
The ShowQueryForm looks like this:
+
 
 +
ShowQueryFormは、次のようにします。
 
<center>[[Image:Mysqlshow.png]]</center>
 
<center>[[Image:Mysqlshow.png]]</center>
and contains a
+
 
 +
下記のようにコントロールを配置します。
 
{|
 
{|
 
|-
 
|-
Line 185: Line 238:
 
| TButton || Caption || Close
 
| TButton || Caption || Close
 
|}
 
|}
The button is placed on the panel.
 
What happens in the "Open Query" OnClick is this. First we create an instance of TShowQueryForm. Secondly we set the DataSet property of the DataSource to our SQLQuery1. Then we set the SQLQuery SQL command to what the user entered in the "Command" editbox and open it. Then the ShowQueryForm is shown modally, this means that it will have the focus of our application until it is closed. When it is closed, we "free" it and close SQLQuery1 again.
 
  
==Sources==
+
ボタンはパネルの上に配置してください。"Open Query"のOnClickで起きることは次の通りです。
 +
まず最初に、TShowQueryFormのインスタンスを生成します。次に、DataSourceのDatasetのプロパティに、SQLQuery1を設定します。それから、SQLQueryにユーザが"Command"エディットボックスで入力したSQLコマンドを設定し、オープンします。そして、ShowQueryFromをモーダル表示させ、クローズされるまでは、フォーカスを維持するようにします。
 +
 
 +
このフォームがクローズされたら、Freeして、SQLQuery1を再びクローズします。
 +
 
 +
==ソースコード==
 
The sources for this project can be downloaded [http://prdownloads.sourceforge.net/lazarus-ccr/mysql_demo_20050408.tar.gz?download here]
 
The sources for this project can be downloaded [http://prdownloads.sourceforge.net/lazarus-ccr/mysql_demo_20050408.tar.gz?download here]
 
For more demo projects see [http://sourceforge.net/project/showfiles.php?group_id=92177&package_id=148359 sourceforge]
 
For more demo projects see [http://sourceforge.net/project/showfiles.php?group_id=92177&package_id=148359 sourceforge]

Latest revision as of 22:09, 6 April 2009

Deutsch (de) English (en) français (fr) 日本語 (ja) polski (pl) slovenčina (sk)

日本語版メニュー
メインページ - Lazarus Documentation日本語版 - 翻訳ノート - 日本語障害情報

Work in progress

はじめに

In the Database tutorialのページで、MySQLサーバーへの最初の接続を試してみる実例があります。 そのときには、ビジュアル、ノンビジュアルの、どんなコンポーネントも使いませんでした。このページでは、(多分)もっと簡単な方法で、MySQLサーバーに接続する方法を紹介します。

利用するコンポーネント

SQLdb Components

$Lazarus/components/sqldbディレクトリに、もうひとつ別のパッケージがあります。 このディレクトリに、sqldblaz.lpkがあります。このパッケージと、Lazarus/components/sqldb/mysql directoryから、mysql4connlaz.lpkをインストールする必要があります。 最初のsqldblaz.lpkは、すべてのデータベースで利用する一般的なコンポーネントを含みます。これらのコンポーネントは、SQLdbタブの中の、TSQLTransactionやTSQLQueryです。mysql4connlaz.lpkをインストールした後では、SQLdbタブにTMySQLConnectionを見つけることができるでしょう。(depicted by a dolphin)

もし、$Lazarus/components/sqldb/mysql ディレクトリや、 mysql4connlaz.lpkを見つけられない場合、mysql4connlaz.lpkがsqldblaz.lpkにマージされた新しいバージョンを使っている事を意味しています。 もしそうだったら、sqldblaz.lpkをインストールすれば、すべてのコンポーネントをLazarusのIDEのツールバーの中に手に入れることができます。

もし、どうやってコンポーネントやパッケージをインストールするか分からなかったら、インストールの方法の解説を呼んでください。 SQLdbコンポーネントはより一般的で、他のデータベースにも接続できるので、たとえば、TMySQLConnectionをTIBConnectionへ置き換えることも可能です。ですから、(より一般的な)SQLdbコンポーネントでプログラムを開発するようにしましょう。

利用したコンポーネントの説明

TMySQLConnection

TMySQLConnectionは、データベースサーバーに接続するパラメータを保存するのに使われます。 接続するのに使われる、接続するホスト、ユーザーID,パスワードをセットします。 TMySQLConnectionのほかのプロパティは、使いたい時に必要に応じて使います。

'LoginPrompt'プロパティは、まだ機能しないので、接続を開始するために必要なHostNameとDatabaseName、UserName、Passwordプロパティは必ず設定してください。

TSQLTransactionを使う場合、MySQLConnectionと同様に、Transactionプロパティを設定してください。さもないと、SQLQueryをオープンすることができません。


ノート:最新のLazarusのSVN版では、MySQLConnectionコンポーネントに3つのバージョンがあります。 それらは、TMySQL40Connection, TMySQL41Connection and TMySQL50Connectionです。

サーバーにあっている正しいものを使うようにしてください。もし、MySQL 4.1を使っているなら、TMySQL41Connectionを使ってください。

TSQLTransaction

SQLTransactionは、内部的な仕事に使われます。SQLTransactionは、あなたがデータセットをオープンするときには、自動的にactivateされます。接続を閉じるときには、関連のあるトランザクションもdeactivateされ、SQLTransactionをつかっているデータセットもcloseされます。

TSQLQuery

TSQLQueryはSQL文を実行するときに使用されます。SQLにSELECT文を設定し、Openメソッドをコールすることで、データを受け取ることができます。または、INSERT,DELETE,UPDATE文で、データを操作することができます。この場合は、Openメソッドではなく、ExecSQLメソッドを使います。

TDataSource

データソースは、DBEditやDBGridといった目に見える「データを表示し操作するコンポーネント(=data aware components)」と、データセットの間の接続を提供します。データソースは、data aware componentに表示するためのデータを提供する役割があります。

データソースは、1度に1つのデータセットに接続されるべきです。しかし、いくつかのdata awareコンポーネントに接続されることがあります。

TDBGrid

DBグリッドはデータセットのデータを表示するのに使われます。DBGridはデータセットに接続するために、データソースを必要とします。データセットがOpenされると、DBグリッドは自動的にデータを表示します。

私達のプログラム

私達がベースとするもの

私達は、ここで作られたものをベースにしたプログラムをつくるようにしましょう。 これは、オリジナル (in English) Chrisによるものをベースにしています。

メインフォーム

私たちは、同じメイン画面を使用し、最初から、すべての機能性を築き上げます。 コンポーネントが本当にすべての面倒なことを取り去ってくれますが、これから、気をつけるべきいろいろな事があります。

それでは、次のような画面を作るところから始めてみましょう。
Trymysql.png
SQLdbタブから、TMySQLConnection、TSQLTransaction,TSQLQuery Components.pngをフォームの上におきます。Connectionコンポーネント以外は、これらのコンポーネントにつけられたデフォルトの名前を変更しないでください。 すべてのバージョンのMySQLに対応するために、MySQL??Connectionには、MySQLConnection1という名前をつけてください。そして、これらのコンポーネントが連携して動作するために、リンクする必要がありますので、次のようにプロパティをセットしてください。

コンポーネント プロパティ
MySQLConnection1 Transaction SQLTransaction1
SQLTransaction1 Database MySQLConnection1
SQLQuery1 Database MySQLConnection1
SQLQuery1 Transaction SQLTransaction1

SQLQuery1のトランザクションのプロパティは、最初にMySQLConnection1のトランザクションプロパティをセットしたときに、自動的に設定されます。

これを設定したら、SQLTransaction1.Databaseに、MySQLConnection1が設定されていることに注意してください。

前にも言いましたが、MySQLサーバーのバージョンにあった正しい接続コンポーネントを使っていることを確認してください。

プログラムコード

スクリーン画像を見てください。プログラムの開始時に有効なボタンは、"Connect to Server"と"Exit"だけです。 その他のボタンが機能するためには、まだ充分な情報がないので、無効になっています。 "Connect to Server"ボタンも、接続先ホスト、ユーザー名、パスワードが与えられるまでは無効にしておく、ということもできますが、この場合、ユーザーは何もすることが無いから、"Exit"を押すしかないな、と考えてしまうでしょう。

まずコードを示す前に、コードには、例外を扱うコードを入れるべきであることを強調したいと思います。

クリティカルなセクションは、

try ... finally

あるいは、

try ... except

の構文に入れるようにしてください。

サーバーに接続する

最初にやることは、サーバーに接続することです。接続する時に、サーバーのどのデータベースが利用可能かどうか知らなければ、実行時の接続するときにデータベースのリストから尋ねるようにできます。 しかしながら、今回は1つを選択し、MySQLConnectionのプロパティの、有効なDatabaseNameを開いて接続するようにしてください。コードの中に、私が使っている"mysql"データベースがあります。 このデータベースはmysqlによって内部的に使われるもので、常に存在します。

procedure TFormTryMySQL.ConnectButtonClick(Sender: TObject);
begin
  // Check if we have an active connection. If so, let's close it.
  if MySQLConnection1.Connected then CloseConnection(Sender);
  // Set the connection parameters.
  MySQLConnection1.HostName := HostEdit.Text;
  MySQLConnection1.UserName := UserEdit.Text;
  MySQLConnection1.Password := PasswdEdit.Text;
  MySQLConnection1.DatabaseName := 'mysql'; // MySQL is allways there!
  ShowString('Opening a connection to server: ' + HostEdit.Text);
  MySQLConnection1.Open;
  // First lets get a list of available databases.
  if MySQLConnection1.Connected then begin
    ShowString('Connected to server: ' + HostEdit.Text);
    ShowString('Retrieving list of available databases.');
    SQLQuery1.SQL.Text := 'show databases';
    SQLQuery1.Open;
    while not SQLQuery1.EOF do begin
      DatabaseComboBox.Items.Add(SQLQuery1.Fields[0].AsString);
      SQLQuery1.Next;
    end;
    SQLQuery1.Close;
    ShowString('List of databases received!');
  end;
end;

まず、最初にチェックすることは、サーバーに接続しているかどうか、そして、プライベートメソッドのCloseConnectionを呼んでいるか、ということです。このメソッドで、いくつかの内部的な処理がおこなわれ、終了します。ボタンをdisableにしたり、チェックボックスやリストボックスをクリアしたりします。 そして、サーバに接続するために必要なパラメータをセットします。

プログラムでは、ShowStringをコールしていることに気が付くでしょう。これは、memoにログのように、文を追加していきます。

パラメータをセットすれば、サーバーに接続できます。これは、次の文をコールすることで実行されます。

MySQLConnection1.Open;

行儀の良いアプリケーションでは、これを例外処理構造にいれて、接続が失敗した場合に、わかりやすいメッセージでユーザーに伝えるべきです。

接続がおこなわれれば、サーバーからデータベースのリストを取得します。サーバーからデータを取得するには、TSQLQueryを使います。SQLプロパティに、SQL文を入れ、サーバーに送ります。MySQLサーバーは、"SHOW DATABASES"コマンドが、データベースのリストを取得するコマンドである、ということを理解します。SQL文をセットしたら、次のようにコールします。

SQLQuery1.Open;

SQLQueryの結果セットは、fieldsプロパティを使って調べることができます。 レコードをイテレーションするために、次のようにコールします。

SQLQuery1.Next;

すべての利用できるデータベースをコンボボックスに追加したら、SQLQueryを再びクローズしてください。

データベースを選択する

ユーザがDatabaseComboBoxからデータベースを選択したときに、"Select Database"ボタンを有効にします。そのボタンのOnClickイベントで、MySQLConnection1のDatabaseNameをセットして、テーブルのリストを要求します。このプロシージャの最後の命令で、"Open Query"ボタンを有効にして、ユーザーが"Command"エディットボックスでクエリを入力でき、サーバに送信できるようにします。

procedure TFormTryMySQL.SelectDBButtonClick(Sender: TObject);
begin
  // A database has been selected so lets get the tables in it.
  CloseConnection(Sender);
  if DatabaseComboBox.ItemIndex <> -1 then begin
    with DatabaseComboBox do
      MySQLConnection1.DatabaseName := Items[ItemIndex];
    ShowString('Retreiving list of tables');
    SQLQuery1.SQL.Text := 'show tables';
    SQLQuery1.Open;
    while not SQLQuery1.EOF do begin
      TableComboBox.Items.Add(SQLQuery1.Fields[0].AsString);
      SQLQuery1.Next;
    end;
    SQLQuery1.Close;
    ShowString('List of tables received');
  end;
  OpenQueryButton.Enabled := True;
end;

MySQLはデータベースのリストを取得する場合と比較して、テーブルのリストを取得するための特別のコマンド"show tables"を持っています。このクエリの結果もデータベースリストと同じように、すべてのテーブルをTableComboBoxに追加していきます。

どうしてこのクエリをオープンする前に、コネクションを再度オープンしなかったのか、疑問に思うかもしれません。 これは、自動的にSQLQueryが有効になったときに、必要に応じて内部的におこなわれるので、必ずしも必要ではありません。

テーブル内のフィールド

MySQLにおいて、テーブルと同様に、テーブルのフィールドを取得する場合にも、"SHOW"を使って、"SHOW COLUMNS FROM <tablename>"とすることでできます。ユーザーがテーブルをTableComboBoxから選択すると、そのComboBoxのOnChangedEventがトリガーとなって、FieldListboxへフィールドの名前を入れます。

procedure TFormTryMySQL.TableComboBoxChange(Sender: TObject);
begin
  FieldListBox.Clear;
  SQLQuery1.SQL.Text := 'show columns from ' + TableComboBox.Text;
  SQLQuery1.Open;
  while not SQLQuery1.EOF do begin
    FieldListBox.Items.Add(SQLQuery1.Fields[0].AsString);
    SQLQuery1.Next;
  end;
  SQLQuery1.Close;
end;

結果セットには、フィールドの名前と同じように、フィールドの型情報、キーになっているかどうか、nullが許されるか、など、色んな情報が含まれています。

データを表示する

データベースに接続するために、コンポーネントを使うという方針と同様に、データを表示するためにも、いくつかのコンポーネントを使ってみましょう。

ユーザーからの要求に応じてデータを表示するグリッドのために、2番目のフォームを使います。 このフォームは、ユーザーが"Command"エディットボックスにSQLコマンドを入力し、"Open Query"ボタンを押した後で表示されるようにします。

これはそのOnClickイベントです。

procedure TFormTryMySQL.OpenQueryButtonClick(Sender: TObject);
begin
  ShowQueryForm := TShowQueryForm.Create(self);
  ShowQueryForm.Datasource1.DataSet := SQLQuery1;
  SQLQuery1.SQL.Text := CommandEdit.Text;
  SQLQuery1.Open;
  ShowQueryForm.ShowModal;
  ShowQueryForm.Free;
  SQLQuery1.Close;
end;

ShowQueryFormは、次のようにします。

Mysqlshow.png

下記のようにコントロールを配置します。

TPanel Align alBottom
TDataSource
TDBGrid Align alClient
DataSource DataSource1
TButton Caption Close

ボタンはパネルの上に配置してください。"Open Query"のOnClickで起きることは次の通りです。 まず最初に、TShowQueryFormのインスタンスを生成します。次に、DataSourceのDatasetのプロパティに、SQLQuery1を設定します。それから、SQLQueryにユーザが"Command"エディットボックスで入力したSQLコマンドを設定し、オープンします。そして、ShowQueryFromをモーダル表示させ、クローズされるまでは、フォーカスを維持するようにします。

このフォームがクローズされたら、Freeして、SQLQuery1を再びクローズします。

ソースコード

The sources for this project can be downloaded here For more demo projects see sourceforge