Adventures of a Newbie/ja

From Free Pascal wiki
Revision as of 19:45, 19 July 2007 by TheCreativeCAT (talk | contribs) (→‎SQLdbを使う: Translation added)
Jump to navigationJump to search

English (en) español (es) 日本語 (ja)

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

私は貴方と同じように初心者です(なんとか使えるようになってからまだたったの五日目)。それが、この文章を書いている理由です。初心者の私はいろんな問題にぶち当たり、これじゃあ途上で倒れてしまった人たちがいるだろうなあと思いました。別に私がみんなより天分に恵まれているとか優秀であるとかいう訳ではなく、単に現実的だったんです。碌でもないことに私は MS Windows からの移行組で、Linux の上で Lazarus を学んでいます。何より最悪なことは、これまで Delphi の経験がなかった、という点です。

着手

インストール

私は SUSE 10.0 を使っています。これは大事な点です。というのも、Novell SUSE は Gnome をサポートする開発用ライブラリをインストールしないからです。実際の所、ほとんどの Linux ディストリビューションは開発用ライブラリをデフォルトではインストールしないのではありませんか。さらにまずいことに、SUSE のデフォルトウィンドウマネジャは KDE です。ここでも問題が発生しました。KDE はグラフィックライブラリとして Qt を利用しているのです。おっと、その前に Lazarus はデフォルトでは GTK グラフィックライブラリを利用するということを書いておくべきでした。2006年3月19日現在、Lazarus 用の Qt ライブラリ(KDE は Qtを使います)を開発しようとしているプログラマもいらっしゃいますけどね。

それで、FPC (Free Pascal Compiler) と Lazarus IDE ファイルをダウンロードする前に、開発用グラフィックライブラリをインストールしなければならないわけです。私の場合は、とても簡単でした。SUSE 10.0 には 'YAST' というユーティリティがあります。YAST を開いてソフトウェアマネジメントのアイコンをつつきます。検索ウィンドウが開き、そこに 'GTK' とタイプして検索します。利用可能な全ての GTK アイテムが表示されるので、全部にチェックを入れてやりました。何が必要なのか全然判っていませんでしたから。YAST が他のパッケージもインストールした方がいいと言ってくるので、OKを押しまくりました。GTK 世界の人なら何が必要なのか正確に分かっているのでしょうが、下手な鉄砲を撃ちまくったのです。単純ですね。

今日、FPC には二つのヴァージョンがあります。私は SUSE 10 からインストールできた方だけしか使えませんでした。しかし Lazarus ウェブサイトでは最新版を入れる方がいいと言われました。

それで、私は FPC と Lazarus の最新のバイナリをダウンロードしました。つまり、ソースからコンパイルする必要がなかったのです。バイナリは 'RPM' というパッケージに入ってきました。ここでもまた YAST を使って両方のパッケージをインストールしました。FPC のウェブサイトに従って、FPC のソースパッケージもダウンロードしました。YAST を使って FPC と FPC ソースの二つをインストールしたのです。次に、Lazarus のパッケージをインストールしました。ここで YAST が文句を言いました。何かが変だといって、GTK+ ライブラリを探していました。それは少し異なる綴でインストールされていました。そこに気づいたら( YAST はエラーを上書きする方法を提供してくれます)、パッケージをインストールすることができ、そいつはうまく走りました。

最初に理解しなければならなかったのは、Lazarus の起動法でした。そう、二つの方法がありました。'startlazarus' と 'lazarus' です。どちらも動きます。'startlazarus' の方が起動が早いようですが。ターミナルウィンドウを開いてどちらかの名前をタイプすればいいのです。あるいはアプリケーションのアイコンを作ることもできます。デスクトップを右クリックしてみてください。

IDE の起動

Lazarus が開きました! もう興奮。ですが、頭が冷えてくると、デフォルトの表示が頭を殴られたくらい気持ち悪いことに気づきました。もちろん、私が比較した相手はこれまで遊んできた kmail のような KDE のプログラムです。なんとかしようと四日間からかいましたよ。後で IDE の見栄えを変える方法を説明することにしましょう。

次の疑問。IDE をどう使えばいいかです。ヘルプをクリックすると、あるウェブサイトに飛ばされます。細い回線を使っているならサイトが表示されるまで少しかかるでしょう。私の場合はサイトが二日間落ちていました。私の作業も足踏みでした。私はウェブに向かって、Delphi のチュートリアルを読んで、どうすればいいかを探りました。Lazarus は Delphi に似せてありますから。これはかなり有効でしたが、私は大声で言わなければなりません。<Lazarus は Delphi ではない>と。次に私は Lazarus フォーラムと FPC フォーラムに加入しました。ですが、すぐに、どちらも大したことが起きていないことに気づきました。なんといっても、FAQ がないのです。次は Lazarus CCR メーリングリストでした。無人とはいいませんが、がらがら。しばらくの間、自分はどうも死にかけのオープンソースプロジェクトに引っかかったようだなあとおもったものです。そこで、Freenode サーバの IRC Lazarus-ide を試してみました。ここにはかなりのユーザがいました。少なくとも励ましにはなりました。

正しいメーリングリストを見つけた

親切な方がいて、どのメーリングリストに行けばいいか教えてもらえました。“lazarus@miraclec.com”。そこではもっと多くのトラフィックがありました。普段だと、私は腰をおちつけてメーリングリストを読み、どんな話をしているか空気を読もうとします。ですが、その時はもう Lazarus の問題に振り回されていたので、速攻で質問を始めました。本当に役に立つ返事がありました。今のうちに指摘しておきたいことがあります。確かにメーリングリストは助けになるものではありますが、質問事項に関し、最低限でも多少はググってみていることが当然だとされます。だが、賭けてもいいのですが、貴方はきっと問題にぶち当たるでしょう。それは Lazarus が Delphi とイコールではないからです。また、IRC に参加する場合はとても気を使う必要があります。そこはほとんどが FPC と Lazarus の開発者の場所です。総じて彼らのグループはフレンドリーですが、新参者にはすぐに怒りだします。

表示の変更

さて IDE の表示をまともにする方法(あるいは gtk2 を使うように構成する方法)です。まず、その方法をどこで見つけたかを書いておきます。フォーラムで読みました。Lazarus パッケージのインストール法につしてのメッセージです(reportlivreが報告)。メッセージが示唆する所では、認証の問題で、パッケージを入れるにはユーザは「ルート」になる必要があるそうでした。そこでルートとしてログインし、tools->configure Lazarus をクリックしました(訳注: Mac OS X の初期状態では root は利用できないようになっており、sudo コマンドの利用が推奨されています。Lazarus を起動する時に sudo ./lazarus とすればいいはずです)。ダイアログボックスが現れ、グラフィックライブラリをいくつか選択できることが判りました。現在の所、必要な全機能(ほとんどあらゆる機能)を実現できるのは gtk1 と gtk2 だけであり、gtk2 を選んで保存しました。次は tools-> Build Lazarus。リビルドが終わって Lazarus を再起動すれば、まるで別の姿になった Lazzrus が現れます。直ぐに問題が発生しました。Novel SUSE 10.0 はデフォルトでは KDE を利用していることを思い出してください。ボタンとメニューの文字の多くが、下の方が切れていました。ググってみると、Utilities->Desktop->Gnome configuration tool->fonts->details and change the resolution to 93 をすればいいことがわかりました(実際にはこの項目を変更すると、gtk-qt-エンジンを再起動することになります)。で、保存です。これで文字の下切れ問題は解決しましたが、再起動毎にこの操作をする必要があります。今の所解決法はわかりません。そんなにコンピュータをシャットダウンしないので、大して問題だとは感じません。どうも GTK2 を使う Lazarus はあまり安定ではないようです。ツールバーのヘンプヒントのような機能も欠けています。結局 GTK1 に戻してしまいました。

次の投稿は、もっと情報のある、プログラミングに関係した内容にするつもりです。

John Fabiani

SQLdbを使う

まず一番大事なことを一つ。これはチュートリアルではありません。チュートリアルの書き方なんて全然知らないのです。これは我が啓蒙の旅の記録、つまりは SQLdb ユニットの使い方をどうやって覚えたかを書いたものです。SQLdb はフォームに貼付けてデータベースアクセスを可能にするコントロールです。

これは新人が書いているもので、あなたのデータベースには当てはまらない情報を含んでいるかも知れないことをご理解ください。私の場合は Posgtres データベースエンジンを使っています。Posgtres はほとんどのプラットフォーム、つまり Linux と Windows で使うことができ、FPC (Free Pascal Compiler) がサポートするデータベースエンジンの一つです。さて警告はこのくらいにして、始めることにしましょう。

最初に、あなたが私のような状況にあるなら、Delphi 用に書かれたデータベースアクセスツールのコマンド説明書 line descriptions を読み始めているだろうと言わせてください。なぜ Delphi かというと、Lazarus が Delphi の様式を受けついているからです。私の場合、それらの説明書で多少ひらめくものもありましたが、なんとも混乱しまくりでした。Delphi のバージョンによって、ツールとデータアクセス法が異なっていることはすぐにわかりました。BDE、dbexpress、zeoslibのようなツールの参考書は Web のそこら中に転がっています。そのため、それらを読む時に、どのバージョンの Delphi を対象にしているのか、あるいは zeos のようなサードパーティ製の(ボーランド製ではない)ツールの話題なのかを、いつも注意深く確認する必要がありました。Kylix 用の説明にも注意しなければなりません。一番忌々しかったのは、そういった説明の中で使われているテクニカルタームでした -- 曰く clientdatasets, sqlqueries, dbexpress datasets, dataset providers, datasnap, data-aware controls。説明書を読み終えるたびに、Lazarus IDE に向かって、それらのコントロールがないものかと探しました。もちろん、ありませんでした。それで、私はこれ — 「論文」、「ハウツー」、「チュートリアル」、「雄叫び」、お好きな呼び方でどうぞ — を書こうと決心したのです。

では Lazarus の SQLdb はどう働くのでしょうか。いつもなら、誰か親切な人たちが理解に役立つよう Web にチュートリアルを書いていてくれているのですが、2006年3月24日の段階ではチュートリアルは見つかりませんでした。{http://wiki.lazarus.freepascal.org/index.php/Lazarus_Database_Tutorial があります} 実際の所、Web には SQLdb コントロールについて書かれたものはほとんどありませんでした。SQLdb のソースコードが(Free Pascal Compiler のソースの中に)ありましたが、Pascal の初心者なので(コメントは多少役立ちましたが)、コードを読むのはほとんど不可能でした。確かに FPC のソースコードフォルダに少し例はあったのです。それらの例に私が気がつかなかったので、SQLdb の作者が Lazarus メーリングリストで教えてくれる有様でした。。そこでこれらの例こそ私が始めた場所だったのです。たった一つだけ私にはアドバンテージがありました。これまでのプログラミング業で、postgres データベースエンジンのことを知っていたことです。かの例と postgres ログのセットアップができることを武器に、私は戦端を開いたのです。

データベースに何かをする前に、そのデータベースと必ず接続しなければなりません。ですから、最初にすることは、Lazarus エディタのツールバーにある SQLdb のタブをクリックすることです。アイコンはいくつかありますが、ここでは Postgres に接続するアイコンだけを考えることにします。象のアイコンです(象は決して忘れない — だから象なんです)。もちろん他のデータベースエンジンもサポートされていますが、前にも言ったように、私は postgres を動かすためのやり方しか知らないのです。話を戻すと、それを選択してフォームにドラッグ&ドロップします。Lazarus がコントロールに名前をつけてくれるので、それをそのまま使うことにしましょう。

Lazarus がつけた名前は 'PQConnection1' でした。異なったデータベースコネクションを使う場合は異なった名前になるでしょう。この名前は自由に変えられます。'PQConnection' をフォームに載せると、オブジェクトインスペクタが開きます(私ならプロパティシートと呼びたい所です)。このオブジェクトインスペクタの中で、いくつかのプロパティないしフィールドを埋める必要があります。'UserName' と 'Password' フィールドを埋めてください。これは問題のデータベースにアクセスできるユーザ名です。次に 'DatabaseName' に接続したいデータベースの名前を入れます。次は 'HostName' です。これはIPアドレスでかまいません。たまたまデータベースエンジンと Lazarus を同じ計算機で走らせている場合は '127.0.0.1' あるいは 'localhost' になるでしょう。

次はなかなかイカしていると思う点です。Lazarus IDE は、接続のセットアップをしている段階でもそれをテストすることができます。'Connected' プロパティを True に変えてください。うまくいくならデータベースエンジンとの接続はオーケーです。エラーメッセージが出る場合は、それを読みましょう。大事な情報があります。ほとんどの問題は SQLdb 接続コントロールではなくデータベースのアクセスにおいて発生します。言い換えれば、データベースアクセスの利用許可 user permission の問題です。

The 'PQConnection1' is like a light switch. Set 'Connected' to 'True' and you have turned on the connection and setting 'Connected' to 'False' and it's off. Like a light switch – on and off. You can also use two procedures 'PQConnection1.open;' is the same as setting 'PQConnection.Connected:=True;' and ' PQConnection1.close;' is the same as setting ' PQConnection1.Connected:=False'. There are many other things you can do with just the ' PQConnection1'. Mostly you can do DDL (Data Definition Language) commands using the 'ExecuteDirect'. There are more properties and methods but I don't know them. However, I do know that the method “OnLogin” does not work as of today.


Next drag a 'TSQLTransaction' icon to the form – Lazarus will name it for you 'SQLTransaction1'. Nowhere did I find an article that even mentions the 'TSQLTransaction'. But the FPC source code helped provide hints. This is what I saw in the code:

   procedure Commit; virtual;
   procedure CommitRetaining; virtual;
   procedure Rollback; virtual;
   procedure RollbackRetaining; virtual;
   procedure StartTransaction; override;
   constructor Create(AOwner : TComponent); override;
   destructor Destroy; override;
   property Handle: Pointer read GetHandle;
   procedure EndTransaction; override;
 

I do know SQL so I could figure out what it did.

StartTransaction = It does a 'begin' but most likely more that just that because the Postgres log suggested other things were occurring but it was not stopping anything I was doing so I did not concern myself it.

EndTransaction = Ends the transaction and is not a 'COMMIT' it is a Rollback.

Commit = commit the transaction.

Rollback = Rollback the Transaction.

I don't know what the following are used for: CommitRetaining, RollbackRetaining.

I think they have something to do with Delphi's BDE tools. If I understand correctly using 'CommitRetaining' or 'RollbackRetaining' will commit or rollback the data but keep the dataset open. Maybe somebody will tell me someday for sure.

All you have to do is set the 'DataBase' property to the connection (remember in the object inspector). In my case that was the 'PQConnection1'. The 'SQLTransaction1' has a property of 'Active'. Again like the 'PQConnection1.Connected' it acts like a light switch to turn off and on the light. However, in this case it (the SQLTransaction1 control) actually sends a 'BEGIN' to the database engine when 'Active' is set to True. And a 'Rollback' when set to 'False'. And just like the 'PQConnection1' you can use ' SQLTransaction1.StartTransaction' and 'StartTransaction.EndTransaction' to do the same thing.

So in other words the ' SQLTransaction1' is nothing more than a way to control SQL transactions. Just like the name of the control implies. So in your code you will need to use the 'Begin','Commit','Rollback' SQL commands at some point. You can do it here in the SQLTransaction control. {this is not exactly right – see text below}

Next comes what I call the SUPER control - the 'TSQLQuery' control. Again drag and drop the control on the form. Fill in the “Database” and the “Transaction” fields by clicking the far right down arrow. In fact if you fill in the “Database” field the “Transaction” field should fill in automatically. Now double click on the “SQL” field and a dialog will open. You will now need to type a simple SQL select statement. Make it something simple – like 'select * from customers'. Save the statement. You will not see the statement in the field. But it is there.

Ok, but what does it do? The object inspector does have the 'Active' property and it acts just like the other control turning off and on the 'SQLQuery' control. I found that the Object inspector was not really a lot of help. But that is where the FPC examples really helped me.

with Fquery do
    begin

    SQL.Clear;
    
    SQL.Add('select * from FPDEV');

    open;
    
    Edit;
    FieldByName('name').AsString := FPdevNames[1];
    FieldByName('birthdate').AsDateTime := FPdevBirthDates[1];
    Post;
    
    Append;
    FieldByName('id').AsInteger := 8;
    FieldByName('name').AsString := FPdevNames[8];
    FieldByName('email').AsString := FPdevEmails[8];
    FieldByName('birthdate').AsDateTime := FPdevBirthDates[8];
    post;
    
    ApplyUpdates;

    end;
  Ftransaction.Commit;

  Fquery.Free;
  Ftransaction.Free;
  Fconnection.Free;
end.

In this example the 'Fquery” is a TSQLQuery control just renamed. Also in this example the connection and the transaction controls are already setup. The 'Fquery' has the 'Database' field set to a connection and the 'Transaction' field set to a transaction. Notice what the example is doing:

  1. The program clears what ever SQL command is in the control with 'SQL.Clear' (this is actually 'Fquery.SQL.Clear')
  2. Next is uses an 'Add' procedure to add a SQL statement. The statement of what will be done.
  3. Then “open”. This will carry out the request. In other words the SQL statement will execute.
  4. “edit” is next and the procedure will allow editing of the data that was retrieved. Works well with datacontrol aware objects.
  5. Next few lines actually change the data by field name.
  6. “post” saves the data to the local cache but does NOT commit the data or send a update statement to the database.
  7. “append” is another example of a routine that SQLQuery has to add a record/tuple or row.
  8. “applyupdate” will send a update statement to the database.
  9. And notice that the actual commit comes from the transaction control (in the example it is 'Ftransaction.commit').
  10. The rest of the commands close the controls with the normal 'free' procedures. Notice the order of the closing.

BTW why is it the super control – check out all the events it has in the object inspector.


Since I have only gotten this far in my understanding I'll stop here. I hope later I can add more knowledge as I attain a better understanding of how to use the SQLdb controls in real programs.

John Fabiani


I'm Back!

Change my thinking or don't use SQLdb.

In the windows world I have always used an ODBC connection to the database engine for my connections from FoxPro. I have come to expect that I controlled when a transaction starts and stops. But in the Delphi/FPC world this is not the way it works. The act of setting the transaction.active:=True; causes the transaction control to send a 'begin' to the database engine. This means if you are just requesting data from the database as in “Select * from sometable” it is done within a SQL transaction. In other words a 'begin' was sent to the database engine. BTW the corresponding “Rollback” or “Commit” is not sent automatically after retrieving the data. So what has to occur is as follows:

transaction.starttransaction; // the same as transaction.active:=true; sqlquery.open; //this already has the sql statement “select * from sometable” transaction.endtransaction; // the same as transaction.active:=False;

This of course is very different than what I'm used too. I sort got my head around using the transaction start and end. But that is not all that is different. Again, in the windows world I only used one connection to the database for everything (well almost everything). So in my coding with FPC I attempted to use one connection (one pqconnection). Man this proved to be difficult. It worked but it was a lot of coding. I asked the mailing list how everyone handled this question (use one connection or use multi connections) I got no response. I'm not sure what that means but I checked the web for delphi examples of data access with multiple forms. In each example (remember these were for delphi) the authors used multiple connections. One for each form. So now I'm using a new connection for each form I open. This actually made the coding much easier. I still had to setup the connection fields (databasename, username,password, etc) in code but the rest of the data access controls can be set at design time and required no setup coding. But what this means is I will more than one connection to the database per each user of my program. Image a user with 10 forms open and ten users. This means I could have 100 connections open to the database engine. Is this important? I know that the Postgres database engine can support thousands of connections. So in the end I guess not. I just have to set a parameter in the Postgres configuration. So I have changed my thinking.

Add a Login Screen

04/17/06 Adding a login screen (splash screen too).

OK so I will need a login screen because my program accesses a database. It has to be the first screen the user will see but not the main screen. My main screen is a form with a bunch of buttons (sort of a menu of buttons) to call other forms and I want it to control and close all the other forms should the user close the main form. So how do I get a form to display before the main screen opens? Searching the internet provided part of the answer. Researching the Lazarus forum provided even more and including the the trick to making a splash screen to work.

In the main program file 'project1.lpr' file is where you add your code. This is the code that starts the program. Yours should look something a like below and mine opens a login form:

program project1;

{$mode objfpc}{$H+}

uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  {$ENDIF}{$ENDIF}
  Interfaces, // this includes the LCL widgetset
  Forms, Controls,
  { add your units here }, menu1, login1, sqlunit, SQLDBLaz, custunit,
contactunit, lookup, vendunit, speciesunit, varietyunit, wareunit, icunit;
   var loginform:Tlogin;
begin
  Application.Initialize;
  loginform:=Tlogin.Create(nil);
  loginform.edit2.text:='johnf';
  if loginform.showmodal <> mrOk then
  begin
  loginform.free;
  loginform:=nil;
  end;

  Application.CreateForm(Tmenuform, menuform);
  Application.Run;
end.

Notice that I create and open a form after the “Application.Initialize;” It is important that your code be added after the 'Application.Initialize;'! The above works as long as I call 'showmodal'. But if I call 'show' the form opens but nothing is displayed in the form. To get it to display correctly just add 'Application.ProcessMessages;' as in the example below.

  Application.Initialize; //this line exists!
  splashScreen := TSplashScreen.Create(nil);
  SplashScreen.ShowOnTop;
  Application.ProcessMessages;  //need this line to allow display
  SplashScreen.Update;
  delay(1000);
  Application.CreateForm(TForm1, Form1);
  SplashScreen.Hide;
  SplashScreen.Free;
  Application.Run;

I'm still learning and I hope more will come. Bye for now.