Lazarus Database Tutorial/ja

From Lazarus wiki
Jump to navigationJump to search

Deutsch (de) English (en) español (es) français (fr) Bahasa Indonesia (id) italiano (it) 日本語 (ja) Nederlands (nl) português (pt) русский (ru) 中文(中国大陆)‎ (zh_CN) 中文(台灣)‎ (zh_TW)

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

概要

このチュートリアルは、Lazarusでいろいろなデータベースの操作を行うためのものです。 Lazarusでは、いくつかのデータベースを外部的にサポートしています。しかし、それぞれのデータベースにたいして開発者は適切なパッケージをインストールしなくてはなりません。 データベースには、コードを書いたり、フォーム上のコンポーネントをドロップしてアクセスすることができます。データアウェアコンポーネントは、DataSourceプロパティをTDatasetに設定することで、接続し、フィールドに対応して表示することができます。データソースはあるテーブルをあらわし、データベースコンポーネント(たとえば、TPSQLDatabase, TSQLiteDataSet)へDataSetプロパティをとおして接続されます。 データアウェアコンポーネントは、IDE上の"Data Controls"タブ上にあり、データソースとデータベースのコントロールは"Data Access"タブ上にあります。

Lazarus と MySQL

MySQLをLinuxやWindowsで動作させる

MySQL User Manualの指示に従って進めてください。

インストール後、mysqldデーモンが動作していることを確認してください。 また、セキュリティをたもちながら、すべての必要なホスト('localhost',ホスト名,ネットワーク上の他のホスト名)から、すべての必要なユーザー(ルート、mysql、あなた自身、他に必要なユーザーを含む)に、必要な権限が与えられているか、確認してください。

、すべての潜在的ユーザ(根、mysql、自分、およびそれを必要とするかもしれない他の誰かを含んでいます)がセキュリティと一致したそのままな同じくらい遠くに必要とされるかもしれないのと('localhost'、地元のホストの名前、あなたのネットワークのいかなる他のホストも含んでいます)同じくらい多くのホストから必要とするのと同じくらい多くの特権を持っているのを確実にしてください。

ルートを含むすべてのユーザがパスワードを持っているのが、望ましいです。 マニュアルにある例でデータベース・システムの機能をテストしてください。 そして、本当にすべてのユーザが信頼できるアクセスができるかチェックしてください。

(訳注:データベースに接続できない場合、プログラムのプロパティの設定が悪い場合もありますが、そもそも、プログラムの前に、インストール、PCの設定、ユーザー、それぞれの権限の設定がきちんとできているか、データベースのサンプルなどであらかじめ確認しておくことが必要です。)

MySQLをFPCのテキストモードで動かしてみよう

例となるフォルダが$(fpcsrcdir)/packages/base/mysql/にあります。 LazarusのIDEで、menu -> Environment Options -> Paths tab -> FPC source directoryにFPCのソースディレクトリがあります。MySQLが置いてある可能性のあるディレクトリは、rpmによるインストールだと、/usr/share/fpcsrc/packages/base/mysql/ Windowsでは C:\lazarus\fpcsrc\packages\base\mysql\です。

このディレクトリには、mysql.pp, mysql_com.pp そして mysql_version.ppがあります。 テストスクリプトを実行する前に、testdbというデータベースを生成する必要があります。 これをおこなうには、MySQL monitorにrootとして、全権限をもってログインして、次のステートメントを発行します。

CREATE DATABASE testdb;

それから、すべて関連しているユーザが適切なアクセス権を持っていることを確認してください。

GRANT ALL ON testdb TO johnny-user IDENTIFIED BY 'johnnyspassword'; 

ここに、いま実行すべきであるmkdbと呼ばれるスクリプトがあります。

sh ./mkdb

システムが、匿名のユーザにデータベースへのアクセスを許可していないとき、これはたぶん失敗するでしょう。 その場合は、エディタをつかって、MySQLがその行を呼び出すように、スクリプトを変更してください。

mysql -u root -p  ${1-testdb} << EOF >/dev/null

そして、再度mkdbを走らせてみます。プロンプトが出たら、パスワードを入力してください。


幸運にも、あなたは何とかテストデータベースを作成したに違いありません。MySQL monitorにログインしている間、 MySQLステートメントを発行して、テストしてください。

select * from FPdev;

そうすると、FPC開発者のID,ユーザー名、電子メールアドレスが表記されているテーブルを見ることができるでしょう。

今度は、testdb.ppというプログラムを実行させてみてください。 (これは、コンパイルしてください。ほとんど最初は失敗するでしょうけど) 私はこのプログラムはいくつかの理由でmysqlに接続できないことを発見しました。

  • 私の環境(SuSE Linux v9.0)で mysql v4.0.15をインストールしました。パッケージが設計されたバージョン3ではありません。
  • プログラムはデータベースにアクセスするためにユーザー名、パスワードが必要です。
  • コンパイラに、どこにmysqlのライブラリを探せばいいか知らせる必要があります。(もしMySQLの開発ライブラリをインストールしていなければ、今インストールしましょう。)

私はオリジナルを修正したくなかったのでtestdb.ppからtrydb.ppと名づけてコピーを作成しました。オリジナルファイルはCVSを使ったアップデートで修正されてしまうからです。

私はさらに、mysql/ver40/というサブディレクトリの中のファイル群を、 メインのmysql/サブディレクトリに、それぞれのファイルの名前が規則性をたもつように、mysql_v4.pp, mysql_com_v4.pp,mysql_version_v4.ppと名前をかえてコピーしました。

私はtrydb.ppのusesを次のように変更しました。

uses mysql_v4

そして、mysql_v4.ppのusesも次のように変更しました。

uses mysql_com_v4

/etc/fpc.cfgに、自分のライブラリを指すように次の行を加えました。

-Fl/lib;/usr/lib

次のステップは、devel-librariesがあなたのためにリンクとしてインストールされている場合、必要ないかもしれませんが、チェックして損はありません。

私は/usr/libディレクトリのmysqlclintライブラリの本当の名前を調べる必要がありました。そして、私の場合、シェルコマンドを発行しました。

ln -s libmysqlclient.so.12.0.0 lmysqlclient

FPCがライブラリを見つけられるよう、シンボリックリンクを生成するために、です。 また、私は次のようなリンクを作成しました。

ln -s libmysqlclient.so.12.0.0 mysqlclient

そして、同じように色々なほかのディレクトリのリンクを設置しました。 厳密には、必要ではないのですが、このケースではそうしました。

他のユーザーでは、次のようなリンクが必要かもしれません。

ln -s libmysqlclient.so.12.0.0 libmysqlclient.so

私はtrydb.ppをユーザーの詳細を含むように修正しました。最初にhost,user,passwordを定数としてもつように。

const
  host : Pchar= 'localhost';
  user : Pchar= 'myusername';
  passwd: Pchar = 'mypassword';

それでも私は、mysql_connect()をコールしても、まだmysqlに接続できないでいました。しかし、より多くのパラメータを必要とするmysql_real_connect()を使うべきだったのです。さらに物事を複雑にしていたのは、多くのパラメータがversion3(パラメータは7個)とversion4(パラメータは8個)の間で変わっているように思えました。

また、mysql_real_connectを使う前に、mysql_init()を使う必要がありました。 これは、オリジナルのmysql.ppにはありませんでしたが、mysql_v4.ppにはあります。

ここまでで、接続するためのコードは次のようになりました。

{ a few extra variables}
var
  alloc : PMYSQL;
 
{main program fragment}
 
begin
 if paramcount=1 then
   begin
   Dummy:=Paramstr(1)+#0;
   DataBase:=@Dummy[1];
   end;
 
Writeln ('Allocating Space...');
 alloc := mysql_init(PMYSQL(@qmysql));
 Write ('Connecting to MySQL...');
 sock :=  mysql_real_connect(alloc, host, user, passwd, database, 0, nil, 0);
 if sock=Nil then
   begin
   Writeln (stderr,'Couldnt connect to MySQL.');
   Writeln (stderr, 'Error was: ', mysql_error(@qmysql));
   halt(1);
   end;
 Writeln ('Done.');
 Writeln ('Connection data:');
{$ifdef Unix}
 writeln ('Mysql_port      : ',mysql_port);
 writeln ('Mysql_unix_port : ',mysql_unix_port);
{$endif}
 writeln ('Host info       : ',mysql_get_host_info(sock));
 writeln ('Server info     : ',mysql_stat(sock));
 writeln ('Client info     : ',mysql_get_client_info);
 
 Writeln ('Selecting Database ',DataBase,'...');
 if mysql_select_db(sock,DataBase) < 0 then
   begin
   Writeln (stderr,'Couldnt select database ',Database);
   Writeln (stderr,mysql_error(sock));
   halt (1);
   end;
{... as original contents of testdb.pp}

それでは、tyrdb.ppのコンパイルを開始する準備はいいですか?

 fpc trydb

成功しました!それでは実行してみましょう。

 ./trydb

おっ!FPC開発者のリストの一覧を得ることができました!

いくつかの、さらなる改善点があります。 ユーザーに関する詳細のエントリを作る時、あるいは、MySQLのコマンドを双方向にしたいとき、定数よりは変数の方がいいでしょう。そして、いくつかの発行したいSQLコマンドに、結果を返さないコマンドでも(full program listingを見てください)ユーザーの詳細情報をコンソールから入力する部分、プログラムがSQLコマンドがコンソールから入力されるループにはいる部分、結果等について、quitがキーボードから入力されるまで、プリントアウトできるようにしてください。

こちらを見てください。Sample Console Listing

LazarusアプリケーションからMySQLへの接続

このチュートリアルでは、基本的なLazarusコンポーネントのみを使って、LazarusでどのようにMySQLに接続するか、そして簡単なクエリを実行するかを示します。 このとき、Data Aware コンポーネントは使いません。しかし、データベースとインターフェースする原理を解説します。

Lazarusで新しいプロジェクトを生成してください。

Project -> New Project -> Application

自動的に生成されたフォームが現れます。 フォームをスクリーンの半分くらいになるように大きくして、フォームの名前とキャプションを、'TryMySQL'としてください。

コンポーネントパレットのStandardのタブから、3つのエディットボックスを、フォームの左上のほうへ置いてください。そして、それぞれのエディットボックスの真上にラベルを置いてください。 ラベルのキャプションを'Host'としてHostLabel,エディットをHostEditとしてください。 同様に、'UserName'としてUserLabel,UserEditとしてください。 同様に、'Password'としてPasswdLabel,PasswdEditとしてください。 これらのかわりに、LabeledEditコンポーネントをAdditionalタブから使うことができます。

PasswdEditを選択して、PasswordCharプロパティを見つけて、これを * か、他のキャラクタにしてください。そうすることで、画面にパスワードをキーボードから入力したときに表示されないように、かわりに、*の文字を表示するようにします。 それぞれのエディットボックスのTextプロパティが空白であることを確認してください。

ここでさらに、もうひとつエディットボックスとラベルを、フォームの右上に置いてください。 ラベルのCaptionを、'Enter SQL Command'に、NameをCommadEditにしてください。

3つのボタンをフォームに置きます。2つは、EditBoxの下の左のほうへ、もう一つは、右のコマンドボックスの下へ置いてください。

左のボタンは、Caption='Connect to Database'、Name='ConnectButton'、もうひとつは、Caption='Exit'、Name='ExitButton'としてください。右のボタンは Caption='Send Query'、Name='QueryButton'としてください。

大きなメモをフォームの右下に貼り付けて、使えるだけのスペースを使って配置して、'Result'と表示してName='ResultMemo'としてください。テキストがあふれたときに自動的にスクロールバーがつくように、ScrollBars='ssAutoBoth'にしてください。また、WordWrap='True'としてください。

Commonコントロールタブから、ステータスバーをフォームの下に置き、SimpleText='TryMySQL'としてください。

このフォームのスクリーンショットを置いておきます。:Mysql Example Screenshot

これで、必要なイベントハンドラを書くことが出来ます。 左にある3つのエディットボックスはホスト名、ユーザ名、パスワードの入力に使います。これらの3つの入力がきちんと終わったら、Connectボタンをクリックします。このボタンのOnClickイベントハンドラは、先ほどのテキストモードのFPCプログラムの一部とほとんど同じです。

データベースからのレスポンスはPascalのwrite文やwriteln文を使って書かれてはいません。しかし、返答はstringsに変換され、Memoに表示されます。Pascalのwriteとwriteln文は沢山の型変換を実行時に行う能力がある一方、Memoを使ってテキストを出力する際に、明確なデータ型変換をstringの正しい形式にすることが必要です。なので、PChar変数はStrPasを使って変換されなければならず、Integer変数はIntToStrを使って変換されなければなりません。

(訳注:Delphiで慣れた方々には当たり前に思えるかもしれませんが、本来、Pascalでの文字列形式出力はwriteやwritelnを使うものであり、それは、実行時に変数の型を明示しなくても、自動的に適切な文字列として表示することができます。)

文字列はMemoに下記のような関数をつかって表示されます。

procedure ShowString (S : string);
(* display a string in a Memo box *)
begin
       trymysqlForm1.ResultsMemo.Lines.Add (S)
end;

Connectボタンのイベントハンドラは次のようにします。

procedure TtrymysqlForm1.ConnectButtonClick(Sender: TObject);
(* Connect to MySQL using user data from Text entry boxes on Main Form *)
var strg: string;
 
begin
 
 dummy1 :=  trymysqlForm1.HostEdit.text+#0;
 host := @dummy1[1];
 dummy2 := trymysqlForm1.UserEdit.text+#0;
 user := @dummy2[1] ;
 dummy3 := trymysqlForm1.PasswdEdit.text+#0;
 passwd := @dummy3[1] ;
 alloc := mysql_init(PMYSQL(@qmysql));
 sock :=  mysql_real_connect(alloc, host, user, passwd, database, 0, nil, 0);
 if sock=Nil then
   begin
     strg :='Couldnt connect to MySQL.'; showstring (strg);
     Strg :='Error was: '+ StrPas(mysql_error(@qmysql)); showstring (strg);
  end
   else
   begin
     trymysqlForm1.statusBar1.simpletext := 'Connected to MySQL';
     strg := 'Now choosing database : ' + database; showstring (strg);
{$ifdef Unix}
     strg :='Mysql_port      : '+ IntToStr(mysql_port); showstring (strg);
     strg :='Mysql_unix_port : ' + StrPas(mysql_unix_port); showstring (strg);
{$endif}
     Strg :='Host info       : ' + StrPas(mysql_get_host_info(sock));
     showstring (strg);
     Strg :='Server info     : ' + StrPas(mysql_stat(sock)); showstring (strg);
     Strg :='Client info     : ' + Strpas(mysql_get_client_info);  showstring (strg);
 
     trymysqlForm1.statusbar1.simpletext := 'Selecting Database ' + DataBase +'...';
 if mysql_select_db(sock,DataBase) < 0 then
 begin
   strg :='Couldnt select database '+ Database; ShowString (strg);
   Strg := mysql_error(sock); ShowString (strg);
 end
 end;
end;

右のテキストボックスはSQL文を入力するものです。終了のセミコロンなしで良いです。 きちんとしたSQL文を入力して、SendQueryボタンを押すとクエリが実行され、ResultMemoの中に結果が表示されます。

SendQueryのイベントハンドラもFPCのテキストモードの時とほとんど同じですが、表示の際に明示的な型変換をおこなうことを除いてという点は、先ほどの例と同じです。

テキストモードのFPCプログラムと違う点は、エラーが検出されたときにプログラムは停止せず、MySQLもクローズされないところです。そのかわり、制御がメインフォームに戻り、コマンドが再発行できるように修正する機会が与えられます。

アプリケーションは最終的に、Exitボタンがクリックされたときに、MySQLをクローズして終了します。 SendQueryは次のようになっています。

procedure TtrymysqlForm1.QueryButtonClick(Sender: TObject);
var
 dumquery, strg: string;
begin
     dumquery := TrymysqlForm1.CommandEdit.text;
     dumquery := dumquery+#0;
     query := @dumquery[1];
     trymysqlForm1.statusbar1.simpletext := 'Executing query : '+ dumQuery +'...';
     strg := 'Executing query : ' + dumQuery; showstring (strg);
     if (mysql_query(sock,Query) < 0) then
     begin
       Strg :='Query failed '+ StrPas(mysql_error(sock)); showstring (strg);
     end
     else
     begin
       recbuf := mysql_store_result(sock);
       if RecBuf=Nil then
       begin
         Strg :='Query returned nil result.'; showstring (strg);
       end
       else
       begin
         strg :='Number of records returned  : ' + IntToStr(mysql_num_rows (recbuf));
         Showstring (strg);
         Strg :='Number of fields per record : ' + IntToStr(mysql_num_fields(recbuf));
         showstring (strg);
         rowbuf := mysql_fetch_row(recbuf);
         while (rowbuf <>nil) do
         begin
              Strg :='(Id: '+ rowbuf[0]+', Name: ' + rowbuf[1]+ ', Email : ' +
               rowbuf[2] +')';
              showstring (strg);
              rowbuf := mysql_fetch_row(recbuf);
         end;
       end;
     end;
end;

プロジェクトを保存して、メニューからRun -> Runを選んでください。

MySQLのソースコードをダウンロードする

全ソースコードは次からダウンロードできます。Sample Source Code

Lazarus と PostGreSQL

これは、Lazarus 0.9.12以降と、PostGresSQLデータベースを、ローカル、リモートの両方でTPQConnectionを使って接続するためのとても短いチュートリアルです。

インストールを正しくおこなったの後で、次のステップをやってみてください。

  • SQLdbタブから、PQConnectionを置く
  • SQLdbタブから、SQLQueryを置く
  • SQLdbタブから、SQLTransactionを置く
  • DataAccessタブから、DataSourceを置く
  • DataControlsタブから、DBGridを置く
  • PQConnectionのプロパティを適切に設定してください。
    • transaction propertyに、SQLTransactionオブジェクトを参照させる。
    • Database name
    • HostName
    • UserName + password
  • SQLTransactionが自動的にPQConnectionを示すように変更されたとこに注意してください。
  • SQLQueryのプロパティを適切に埋めてください。
    • transaction プロパティに適切なオブジェクト
    • database プロパティに適切なオブジェクト
    • SQL (たとえば、'select * from anytable' などとしてください。)
  • DataSourceオブジェクトのDataSetプロパティに、SQLQueryオブジェクトを指定してください。
  • DBGridオブジェクトのDataSourceプロパティにDataSourceオブジェクトを設定してください。

すべてをconnectedとactiveにすると、設計時においても、DBGridに表示がされます。 TDBTextとTDBEditは、私には、ただ値を表示するだけのように見えます。

To change contents in the database, I called the DB Engine direct with the following code: データベースの内容を更新するには、私は次のようにDBエンジンをダイレクトに呼び出します。

 try
   sql:= 'UPDATE table SET setting=1';
   PQDataBase.Connected:=True;
   PQDataBase.ExecuteDirect('Begin Work;');
   PQDataBase.ExecuteDirect(sql);
   PQDataBase.ExecuteDirect('Commit Work;');
   PQDataBase.Connected:=False;
 except
   on E : EDatabaseError do
     MemoLog.Append('DB ERROR:'+sql+chr(13)+chr(10)+E.ClassName+chr(13)+chr(10)+E.Message);
   on E : Exception do
     MemoLog.Append('ERROR:'+sql+chr(13)+chr(10)+E.ClassName+chr(13)+chr(10)+E.Message);
 end;


  • ノート:
    • Lazarus 0.9.12 + PGSQL 8.3.1にて、Windowsでテストしました。
    • Lazarus 0.9.12 and PGSQL 8.0.xで、Linuxでテストしました。


  • インストレーションとエラー:
    • Lazarus 0.9.12のテストバージョン では、"text" と "numeric" の型にバグがあります。
    • 固定長のキャラクタと、intとfloat8では、私は問題なく使えました。
    • 時々Lazarusを再起動することでくだらないエラーを解決できた
    • いくつかのエラーの後で、トランザクションがアクティブのまま残り、手動でデアクティベートしなくてはならなかった。
    • Lazarusによって行われた変更は、もちろん、トランザクションがコミットされるまでは見ることができません。(訳注:他のトランザクションでは、ということ)
    • IDEのデバッガは(少なくともWindowsにおいては)バグがあるようです。時々IDEの外で走らせるとエラーの発生を見つけるのに役立ちます。
    • Linuxでは、特定のエラーメッセージがコンソールに出力されることがあります。--もし、コマンドラインで走らせているなら、時々デバッグに役立つ情報があります。
    • このようなエラーが発生することがあります。: "Can not load Postgresql client. Is it installed (libpq.so) ?"
      • PostgreSQLをインストールした所から、libpq*を探して、パスに加えて下さい。
      • Linuxでは、pathにlibpq.soファイルを、/etc/fpc.cfgの中のライブラリセクションに加えてください。たとえば、次のように:-Fl/usr/local/pgsql/lib
      • Windowsでは、これらのライブラリを、環境変数のパスのどこにでも追加してください。また、プロジェクトディレクトリに加えてもかまいません。
      • 私は、すべてのDLLを自分のパソコンのC:\Program Files\PostgreSQL\8.1\bin などに入れて、パスを通しています。

Lazarus と SQLite

by Luiz Américo

Introduction

TSqliteDataset and TSqlite3Dataset are TDataset descendants that access, respectively, 2.8.x and 3.2.x sqlite databases. Below is a list of the principal advantages and disadvantages:

Advantages:

  • Flexible: programmers can choose to use or not to use the SQL language, allowing them to work with simple table layouts or any complex layout that SQL/sqlite allows
  • Automatic database update: no need to update the database manually with SQL statements, a single method take cares of it
  • Fast: it caches the data in memory, making browsing in the dataset fast
  • No server instalation/configuration: just ship together with sqlite dynamic library

Disavantages

  • Requires external file (sqlite library)

Requirements

  • For sqlite2 databases:
    • fpc 2.0.0
    • Lazarus 0.9.10
    • sqlite runtime library 2.8.15 or above (get from www.sqlite.org)
  • For sqlite3 databases:
    • fpc 2.0.2
    • Lazarus 0.9.11 (svn revision 8443 or above)
    • sqlite runtime library 3.2.1 or above (get from www.sqlite.org)

Before initiating a lazarus projects, ensure that:

  • the sqlite library is on the system PATH or in the executable directory
  • under Linux, put cmem as the first unit in uses clause of the main program

How To Use (Basic Usage)

Install the package found at /components/sqlite directory (see instructions here)

At design time set the following properties:

  • FileName: path of the sqlite file [required]
  • TableName: name of the table used in the sql statement [required]
  • Sql: a SQL select statement [optional]

Creating a Table (Dataset)

Double click in the component icon or use the 'Create Table' item of the popup menu that appears when clicking the right mouse button. A simple self-explaining table editor will be show.

 Here is all field types supported by TSqliteDataset and TSqlite3Dataset: 
 
 Integer
 AutoInc
 String
 Memo
 Bool 
 Float
 Word
 DateTime
 Date
 Time
 LargeInt
 Currency
 

Retrieving the data

After creating the table or with a previously created Table, open the dataset with Open method. If the SQL property was not set then all records from all fields will be retrieved, the same if you set the SQL to:

 SQL:='Select * from TABLENAME'; 

Applying changes to the underlying datafile

To use the ApplyUpdates function, the dataset must contain at least one field that fills the requirements for a Primary Key (values must be UNIQUE and not NULL)

It's possible to do that in two ways:

  • Set PrimaryKey property to the name of a Primary Key field
  • Add an AutoInc field (This is easier since the TSqliteDataSet automatically handles it as a Primary Key)

If one of the two conditions is set then just call

 ApplyUpdates;

PS1: If both conditions are set, the field corresponding to PrimaryKey is used to apply the updates.

PS2: Setting PrimaryKey to a field that is not a Primary Key will lead to loss of data if ApplyUpdates is called, so ensure that the chosen field contains not Null and Unique values before using it.

Remarks

  • Although it has been tested with 10000 records and worked fine, TSqliteDataset keeps all the data in memory, so remenber to retrieve only the necessary data (principally with Memo Fields).
  • The same datafile (Filename property) can host several tables/datasets
  • Several datasets (different combinations of fields) can be created using the same table simultaneously
  • It's possible to filter the data using WHERE statements in the sql, closing and reopening the dataset (or calling RefetchData method). But in this case, the order and number of fields must remain the same
  • It's also possible to use complex SQL statements using aliases, joins, views in multiple tables (remember that they must reside in the same datafile), but in this case ApplyUpdates won't work. If someone wants to use complex queries and to apply the updates to the datafile, mail me and I will give some hints how to do that
  • Setting filename to a sqlite2.x datafile not created by TSqliteDataset and opening it is allowed but some fields won't have the correct field type detected. These will be treated as string fields.

Generic examples can be found at fpc/fcl/db/sqlite CVS directory

Luiz Américo pascalive(at)bol(dot)com(dot)br

Lazarus と MSSQL

これはZeoslib (latest cvs)でおこなっています。ページの最後のリンクを見てください。

Lazarus と Interbase / Firebird

Install Packagesを見て下さい。このページにはどのようにIBやFBサーバーと接続するか、最初の小さいサンプルと説明があります。

この作業も最新のZeoslibにあります。

FBLib Firebird ライブラリ

[1] is an open Source Library No Data Aware for direct access to Firebird Relational Database from Borland Delphi / Kylix, Freepascal and Lazarus.

Current Features include:

  • Direct Access to Firebird 1.0.x 1.5.x Classic or SuperServer
  • Multiplatform [Win32,Gnu/Linux,FreeBSD)
  • Automatic select client library 'fbclient' or 'gds32'
  • Query with params
  • Support SQL Dialect 1/3
  • LGPL License agreement
  • Extract Metadata
  • Simple Script Parser
  • Only 100-150 KB added into final EXE
  • Support BLOB Fields
  • Export Data to HTML SQL Script
  • Service manager (backup,restore,gfix...)
  • Events Alerter

You can download documentation on FBLib's website.

Lazarus と dBase

Tony Maro

You might also want to visit the beginnings of the TDbf Tutorial page

FPC includes a simple database component that is similar in function to the Delphi TTable component called "TDbf" (TDbf Website) that supports a very basic subset of features for dBase files. It is not installed by default, so you will first need to install the Lazarus package from the "lazarus/components/tdbf" directory and rebuild your Lazarus IDE. It will then appear next to the TDatasource in your component palette.

The TDbf component has an advantage over other database components in that it doesn't require any sort of runtime database engine, however it's not the best option for large database applications.

It's very easy to use. Simply, put, drop a TDbf on your form, set the runtime path to the directory that your database files will be in, set the table name, and link it to your TDatasource component.

Real functionality requires a bit more effort, however. If a table doesn't already exist, you'll need to create it programmatically, unless there's a compatible table designer I'm not familiar with.

Attempting to open a non-existant table will generate an error. Tables can be created programmatically through the component after the runtime path and table name are set.

For instance, to create a table called "dvds" to store your dvd collection you would drop it on your form, set the runtime path, and set the table name to "dvds". The resulting file will be called "dvds.dbf".

In your code, insert the following:

   Dbf1.FilePathFull := '/path/to/my/database';
   Dbf1.TableName := 'dvds';
   With Dbf1.FieldDefs do begin
       Add('Name', ftString, 80, True);
       Add('Description', ftMemo, 0, False);
       Add('Rating', ftString, 5, False);
   end;
   Dbf1.CreateTable;

When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data.

Adding indexes is a little different from your typical TTable. It must be done after the database is open. It's also the same method you use to rebuild the indexes. For instance:

   Dbf1.Exclusive := True;
   Dbf1.Open;
   Dbf1.AddIndex('dvdsname','Name',[ixPrimary, ixUnique, ixCaseInsensitive]);
   Dbf1.AddIndex('rating.ndx', 'Rating', [ixCaseInsensitive]);
   Dbf1.Close;

The first (primary) index will be a file called "dvdsname.mdx" and the second will be a file named "rating.ndx" so in a multiple table database you must be careful not to use the same file name again.

I will try to add a more detailed example at a later date, but hopefully this will get those old Delphi programmers up and running with databases in Lazarus!

関連のある記事

https://trac.synsport.com:8000/index.php/pdo/wiki (username/password is guest/guest)

Contributors and Changes

This page has been converted from the epikwiki version.