Sign in Join
Wiki copytemporary

Lazarus Database Tutorial/zh TW: what changed

Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11# Lazarus 資料庫教學
22
33## 導覽
44
55本教材內容是關於如何於 Lazarus 下配合數種資料庫來工作。
66
77Lazarus 支援數種非內建資料庫,而開發者仍應安裝各資料庫所對應的元件(Packages)。你可以透過程式碼或直接拉元件(components)至表單(from)來存取資料庫。資料感知 (data-aware) 元件代表資料庫欄位,並透過 TDataSource 設定指定的資料來源 (DataSource) 屬性物件來連接。資料來源代表一個資料表,是以連接至資料庫元件 (如:TPSQLDatabase, TSQLiteDataSet) 的 DataSet 屬性所選定的。資料感知元件位於「資料控制」籤頁內。資料來源及資料庫控制元件則位於「資料存取」的籤頁內。
88
99## Lazarus 與 MySQL
1010
1111### 讓 MySQL 在 Linux 或 Windows 中動起來
1212
1313照著 MySQL 使用手冊裡的指示,讓 mysqld 程序於背景執行。對於所有潛在的主機來源 (包含本機 'localhost',本機的名稱和其他透過網路連線的主機),所有的用戶 (包含根使用者,mysql,你自己和其他所有會用到的人) 都要設定使用權限。也要儘可能的達到安全性要求,所有使用者,包含根使用者都要有一個密碼。接著使用手冊上的範例方法來測試確定所有使用者在系統上的權限都安全可靠。
1414
1515### 在文字模式中讓 MySQL 為 FPC 工作
1616
17-在 \$(fpc<b>src</b>dir)/packages/base/mysql/ 資料夾中有一個範例程式。你可以在 Lazarus 的 fpc 原始碼資料夾中找到:〔環境〕選單 -\> 〔環境〕選項 -\> 〔路徑〕籤頁 -\>〔FPC 原始碼目錄〕。 mysql 的範例資料夾可能的路徑為 /usr/share/fpcsrc/packages/base/mysql/ (rpm 安裝) 或者 C:\lazarus\fpcsrc\packages\base\mysql\\ (Windows)。 這個資料夾也包含了 mysql.pp, mysql_com.pp 和 mysql_version.pp。 執行這些指令碼前,你必須先建立一個 testdb 資料庫:請登入 mysql 監視器 (以根使用者登入來取得完整權限) 並執行以下 SQL 指令
17+在 \$(fpcsrcdir)/packages/base/mysql/ 資料夾中有一個範例程式。你可以在 Lazarus 的 fpc 原始碼資料夾中找到:〔環境〕選單 -\> 〔環境〕選項 -\> 〔路徑〕籤頁 -\>〔FPC 原始碼目錄〕。 mysql 的範例資料夾可能的路徑為 /usr/share/fpcsrc/packages/base/mysql/ (rpm 安裝) 或者 C:\lazarus\fpcsrc\packages\base\mysql\\ (Windows)。 這個資料夾也包含了 mysql.pp, mysql_com.pp 和 mysql_version.pp。 執行這些指令碼前,你必須先建立一個 testdb 資料庫:請登入 mysql 監視器 (以根使用者登入來取得完整權限) 並執行以下 SQL 指令
1818
1919`CREATE DATABASE testdb;`
2020
2121接著確認所有相關使用者擁有適當的存取權限
2222
2323`GRANT ALL ON testdb TO johnny-user IDENTIFIED BY 'johnnyspassword'; `
2424
2525現在你應試著去執行一個叫 mkdb 的指令碼:
2626
2727`sh ./mkdb`
2828
2929這個指令應該會失敗, 因為系統不會允許匿名者存取資料庫。所以必須修改這個指令碼讓 mysql 讀取以下這行:
3030
3131`mysql -u root -p  ${1-testdb} << EOF >/dev/null`
3232
3333接著試著再執行一次,系統提示要你輸入密碼。幸運的話你應該就可以管理剛建立的資料庫了。用以下的 mysql 指令測試一下(在 mysql 監視器中):
3434
3535`select * from FPdev;`
3636
3737即可看到一個列有 ID,使用者名稱和 Email 地址的FPC 開發者資料表了。
3838
3939現在可以執行測試程式 testdb.pp 了 (這檔也許還需要先編譯過,而且可能會在第一次編譯出錯!!)。
4040
4141我找出這支程式可能無法連結 MySQL 的幾個原因:
4242
4343- 我的系統 (SuSE Linux v9.0) 安裝的是 mysql v4.0.15,不同於安裝套件的版本 3。
4444
4545- 程式需要輸入使用者和密碼來存取資料庫。
4646
4747- 編譯器需要知道哪裡可以找到 MySQL 的函式庫 (**如果你並沒有安裝 MYSQL 的開發函式庫,那現在快裝!**)
4848
4949我將 testdb.pp 另存成 trydb.pp,然後做修改 - 這樣代表原來那支還是可以隨後透過 CVS 更新。 我另外也將在 mysql/ver40/ 子目錄下找到的那支另存成 mysql_v4.pp,mysql_com_v4.pp 和 mysql_version_v4.pp,記得你單元裡的程式也要改成適當的檔名。在 trydb.pp 裡我變更 uses 敘述句為
5050
5151`uses mysql_v4`
5252
5353mysql_v4.pp 的敘述句改為
5454
5555`uses mysql_com_v4`
5656
5757另外為要使用的函式庫加入一行到 /etc/fpc.cfg 裡:
5858
5959`-Fl/lib;/usr/lib`
6060
6161接下來的動作也許不必要做,因為你在安裝開發函式庫的時候應該會自動幫你建立連結,但檢查一下總是無仿。 進行前需要先找到我的 MYSQL 用戶端函式庫是放在 /usr/lib 目錄下面的哪裡,我的狀況是先下 shell 指令:
6262
6363`ln -s libmysqlclient.so.12.0.0 lmysqlclient`
6464
6565建立一個軟連結讓 FPC 可以找的到函式庫。為了更準確一些我再建立一個連結
6666
6767`ln -s libmysqlclient.so.12.0.0 mysqlclient`
6868
6969然後放一個相同的連結在不同的其他目錄裡:不是必需,視請況而定! 然後有些使用者也許會需要增加如下的連結:
7070
7171`ln -s libmysqlclient.so.12.0.0 libmysqlclient.so`
7272
7373我修改 trydb.pp 的內容,含括進使用者連線資訊,從上到下計的內容有主機,使用者與密碼:
7474
7575`const`\
7676`  host : Pchar= 'localhost';`\
7777`  user : Pchar= 'myusername';`\
7878`  passwd: Pchar = 'mypassword';`
7979
8080我還發現我忽叫 mysql_connect() 還是無法連上 MySQL,但使用 mysql_real_connect() ,加上一堆參數後就可以了。未來還會更複雜,參數的數目似乎從 3 版(七個)換到 4 版(八個)還有變化。在使用 mysql_real_connect 之前我還得先使用 mysql_init(),但這在原始的 mysql.pp 裡並找不到,但出現於 mysql_v4.pp。
8181
8282所以連線的程式碼將會是現在這樣:
8383
8484`{加一些額外的變數}`\
8585`var`\
8686`  alloc : PMYSQL;`\
8787` `\
8888`{主程式片段}`\
8989` `\
9090`begin`\
9191` if paramcount=1 then`\
9292`   begin`\
9393`   Dummy:=Paramstr(1)+#0;`\
9494`   DataBase:=@Dummy[1];`\
9595`   end;`\
9696` `\
9797`Writeln ('分派空間...');`\
9898` alloc := mysql_init(PMYSQL(@qmysql));`\
9999` Write ('連線到 MySQL...');`\
100100` sock :=  mysql_real_connect(alloc, host, user, passwd, database, 0, nil, 0);`\
101101` if sock=Nil then`\
102102`   begin`\
103103`   Writeln (stderr,'無法連線到 MySQL.');`\
104104`   Writeln (stderr, '錯誤是:', mysql_error(@qmysql));`\
105105`   halt(1);`\
106106`   end;`\
107107` Writeln ('完成。');`\
108108` Writeln ('連線資料:');`\
109109`{$ifdef Unix}`\
110110` writeln ('Mysql_port      : ',mysql_port);`\
111111` writeln ('Mysql_unix_port : ',mysql_unix_port);`\
112112`{$endif}`\
113113` writeln ('Host info       : ',mysql_get_host_info(sock));`\
114114` writeln ('Server info     : ',mysql_stat(sock));`\
115115` writeln ('Client info     : ',mysql_get_client_info);`\
116116` `\
117117` Writeln ('選擇資料庫 ',DataBase,'...');`\
118118` if mysql_select_db(sock,DataBase) < 0 then`\
119119`   begin`\
120120`   Writeln (stderr,'無法選取資料庫 ',Database);`\
121121`   Writeln (stderr,mysql_error(sock));`\
122122`   halt (1);`\
123123`   end;`\
124124`{... 其他就如原來 testdb.pp 裡的內容}`
125125
126126現在 - 準備好開始編譯 trydb.pp 了嗎?
127127
128128` fpc trydb`
129129
130130成功!現在執行:
131131
132132` ./trydb`
133133
134134哇!我讀取到 FPC 開發者的清單了!
135135
136136想要更精進的話:將使用者連線資訊的部份與 MySQL 的指令做成互動的模式,使用變數而不使用常數,如此可以在你退出 MySQL 前輸入多個 SQL 指令:參見[[Lazarus Database Tutorial/TryDbpp|所有程式一覽表]],當使用者資訊是從主控台模式輸入取得時,程式將要利用迴圈,讓 SQL 的指令可以重覆輸入 (可以不用分號做結尾),然後再將回應顯示出來,直到使用者鍵入 'quit' 為止。
137137
138138參見[[Lazarus Database Tutorial/SampleListing|主控台範例一覽表]]。
139139
140140### 在 Lazarus 的應用程式裡連線到 MySQL
141141
142142此教學將示範 Lazarus 如何連線到 MySQL 資料庫,並執行一段簡單的查詢,僅止使用 Lazarus 基本的元件;它並沒有用到任何資料感知元件,但已可想像連線到資料庫其介面的原理。
143143
144144建立一個新的 Lazarus 專案:
145145
146146`〔專案〕->〔新專案〕->〔應用程式〕`
147147
148148將會自動產生出一份表單。
149149
150150先把表單拉大到約半個畫面的大小,然後將表單的標題改名為 'TryMySQL'。
151151
152152從標準元件的籤頁裡放置三個編輯方框到表單的左上,然後緊接著其下各放一個標籤。將標籤的標題改為「主機」(還有 HostLabel,HostEdit),「使用者名稱」 (還有 UserLabel,UserEdit) 和「密碼」 (還有 PasswordLabel 和 PasswordEdit)。或是你可以使用附加籤頁裡的標籤編輯元件來取代。
153153
154154選取密碼編輯的方框,找到 PasswordChar 這個內容:將其改為 * 或是其他字元,這樣當你鍵入你的密碼時你的畫面就會重覆顯示你這個字元來取代你真正的密碼。然後確定 Text 內容裡的值皆是空的。
155155
156156然後現在再放置一個編輯方框和標籤到你表單的右上方。改變標籤成「輸入 SQL 命令」,並命名為 CommandEdit。
157157
158158表單上再放三個按鈕:兩個在左邊,編框框的下面,另一個在右邊,命令框的下面。
159159
160160將左邊的按鈕標記為「連結到資料庫」(ConnectButton) 與「離開」(ExitButton),而右邊的那個記為「送出查尋」(QueryButton)。
161161
162162再放一個大的記事框在右下,標名為「結果」(ResultMemo),把送下能利用的空間都填滿給它。找到它捲軸條(ScrollBars)的內容,選為 ssAutoBoth,這樣捲軸條就可以為出現的文字自動調整空間。然後文字換行 (WordWrap) 的內容設為真 (True)。
163163
164164再放一個狀態列 (從共通控制項籤頁裡) 在表單的下面,然後將其單純的文字 (SimpleText) 內容裡設為 'TryMySQL'。
165165
166166擷圖將顯示表單長這個樣子:[Mysql 範例擷圖](http://lazarus-ccr.sourceforge.net/kbdata/trymysqldb.png)
167167
168168現在我們要寫一些事件處理器。
169169
170170這三個編輯框是用來輸入主機名稱,使用者名稱和密碼用的。當這三個都已輸入滿足條件後,將按下連線的按鈕。因此這按鈕 OnCLick 在事件處理器裡就是將在處理上述文字模式的 FPC 程式裡做的事情。
171171
172172而資料庫回傳的訊息,現在就不能用 Pascal 的 write 和 writeln 這兩個敘述句來負責了:取而代之的是所有回應都將轉成字串然後丟到記事框裡。鑑於 Pascal 的 write 和 writeln 敘述句能「即時」地將資料型態轉換,因為在記事框要輸出的文字,在處理時也要能不含糊地都轉換成字串才送出,所以字元變數就要用 StrPass 轉換成字串變數,而數字就要用 IntToStr 去轉換。
173173
174174在記事框裡顯示字串時將用
175175
176176`procedure ShowString (S : string);`\
177177`(* display a string in a Memo box *)`\
178178`begin`\
179179`       trymysqlForm1.ResultsMemo.Lines.Add (S)`\
180180`end;`
181181
182182連線按鈕的事件處理器將會變成:
183183
184184`procedure TtrymysqlForm1.ConnectButtonClick(Sender: TObject);`\
185185`(* 使用主表單裡文字框裡輸入的使用者訊息來連線到 MySQL *)`\
186186`var strg: string;`\
187187` `\
188188`begin`\
189189` `\
190190` dummy1 :=  trymysqlForm1.HostEdit.text+#0;`\
191191` host := @dummy1[1];`\
192192` dummy2 := trymysqlForm1.UserEdit.text+#0;`\
193193` user := @dummy2[1] ;`\
194194` dummy3 := trymysqlForm1.PasswdEdit.text+#0;`\
195195` passwd := @dummy3[1] ;`
196196
197197` alloc := mysql_init(PMYSQL(@qmysql));`\
198198` sock :=  mysql_real_connect(alloc, host, user, passwd, database, 0, nil, 0);`\
199199` if sock=Nil then`\
200200`   begin`\
201201`     strg :='無法連線到 MySQL.'; showstring (strg);`\
202202`     Strg :='錯誤是:'+ StrPas(mysql_error(@qmysql)); showstring (strg);`\
203203`  end`\
204204`   else`\
205205`   begin`\
206206`     trymysqlForm1.statusBar1.simpletext := 'Connected to MySQL';`\
207207`     strg := '現在選擇資料庫:' + database; showstring (strg);`\
208208`{$ifdef Unix}`\
209209`     strg :='Mysql_port      : '+ IntToStr(mysql_port); showstring (strg);`\
210210`     strg :='Mysql_unix_port : ' + StrPas(mysql_unix_port); showstring (strg);`\
211211`{$endif}`\
212212`     Strg :='Host info       : ' + StrPas(mysql_get_host_info(sock));`\
213213`     showstring (strg);`\
214214`     Strg :='Server info     : ' + StrPas(mysql_stat(sock)); showstring (strg);`\
215215`     Strg :='Client info     : ' + Strpas(mysql_get_client_info);  showstring (strg);`\
216216` `\
217217`     trymysqlForm1.statusbar1.simpletext := '選取資料庫 ' + DataBase +' 中...';`\
218218` if mysql_select_db(sock,DataBase) < 0 then`\
219219` begin`\
220220`   strg :='無法選取資料庫 '+ Database; ShowString (strg);`\
221221`   Strg := mysql_error(sock); ShowString (strg);`\
222222` end`\
223223` end;`\
224224`end;`
225225
226226右方的文字框是用來輸入 SQL 語法的,不用在結尾加分號;當你輸入內容滿足語法條件是,按下送出查詢 (SendQuery) 按鈕,查詢即進行處理,然後結果都會寫進記事框 (ResultBox) 內。
227227
228228而送出查詢按鈕在事件處理器裡要做的事也跟先前在 FPC 文字模式裡寫的一樣,但除了在字串回傳後要丟上記事框內之前,其型態轉換不得含糊。
229229
230230這和文字模式的 FPC 程式唯一不一樣的地方在於當一但偵測到錯誤狀態時,程式不會中斷,MySQL 也不會關閉,取而代之的是事件處理又回到主表單,等待新的查詢再重新送出。程式只有在按下「離開」按鈕後,才會關閉 MySQL 的連線與整個應用程式。 送出查詢 (SendQuery) 按鈕的程式碼如下:
231231
232232`procedure TtrymysqlForm1.QueryButtonClick(Sender: TObject);`\
233233`var`\
234234` dumquery, strg: string;`\
235235`begin`\
236236`     dumquery := TrymysqlForm1.CommandEdit.text;`\
237237`     dumquery := dumquery+#0;`\
238238`     query := @dumquery[1];`\
239239`     trymysqlForm1.statusbar1.simpletext := '執行查詢中:'+ dumQuery +'...';`\
240240`     strg := '執行查詢中:' + dumQuery; showstring (strg);`\
241241`     if (mysql_query(sock,Query) < 0) then`\
242242`     begin`\
243243`       Strg :='查詢失敗 '+ StrPas(mysql_error(sock)); showstring (strg);`\
244244`     end`\
245245`     else`\
246246`     begin`\
247247`       recbuf := mysql_store_result(sock);`\
248248`       if RecBuf=Nil then`\
249249`       begin`\
250250`         Strg :='查詢回傳的內容為空。'; showstring (strg);`\
251251`       end`\
252252`       else`\
253253`       begin`\
254254`         strg :='回傳資料筆數:' + IntToStr(mysql_num_rows (recbuf));`\
255255`         Showstring (strg);`\
256256`         Strg :='欄位記錄數:' + IntToStr(mysql_num_fields(recbuf));`\
257257`         showstring (strg);`\
258258`         rowbuf := mysql_fetch_row(recbuf);`\
259259`         while (rowbuf <>nil) do`\
260260`         begin`\
261261`              Strg :='(Id: '+ rowbuf[0]+', Name: ' + rowbuf[1]+ ', Email : ' +`\
262262`               rowbuf[2] +')';`\
263263`              showstring (strg);`\
264264`              rowbuf := mysql_fetch_row(recbuf);`\
265265`         end;`\
266266`       end;`\
267267`     end;`\
268268`end;`
269269
270270儲存你的專案,然後按〔執行〕-\>〔執行〕
271271
272272#### 下載 MYSQL 原始碼
273273
274274所有程式的一覽表都可以在這裡取得:[範例程式碼](http://lazarus-ccr.sourceforge.net/kbdata/mysqldemo.tar.gz)
275275
276276## 使用 TMySQL50Connection 元件的簡單 MySQL 示範
277277
278278這程式碼是一個簡單快速的示範 (在 Win XP 下使用 Lighty2Go 執行)。libmysql.dll 放入 Lazarus 的專案,同樣置於與 lazarus.exe 相同的目錄裡 (可在 Lighty2Go 目錄下取得)。這裡在你的表單裡,除了三個編輯框,一個記事框和幾個按鈕外你什麼元件也不用再加進去。你先必須在 uses 敘述句裡加入 mysql50conn 和 sqldb 這兩項。Lazarus 放元件的目錄對於程式設計師的權限是可讀取和寫入 (rw)。MySQL dbm 使用者預設為 'root' 並沒有密碼,在一個名為 test1 的資料庫裡與名為 tPerson 的表格裡有三個欄位:personid (int),surname (varchar(40)) 與 dob (datetime)。使用 phpMyAdmin (Lighty2Go 裡) 來建立資料庫,表格與欄位,然後插入一些測試資料。注意到在 phpMyAdmin 裡的日期應打成 年年年年-月月-日日,不過我們下面建立的程式可以輸入一般格式的日期。在連線之前要先按 btnTest 按鈕,請注意每一行內容都可以套用更新-若不這麼做則這些資料不會再寫回資料庫裡,只是存放在記憶體內,用 btnFirst 和 btnNext 兩個按鈕來切換觀看。
279279
280280 unit unt_db;
281281 //範例來源:
282282 //http://www.lazarus.freepascal.org/index.php?name=PNphpBB2&file=viewtopic&t=5761
283283 //來自論壇的 tpglemur
284284 {$mode objfpc}{$H+}
285285 interface
286286 uses
287287 Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,
288288 mysql50conn, sqldb, StdCtrls;
289289 type
290290 { TForm1 }
291291 TForm1 = class(TForm)
292292 btnTest: TButton;
293293 btnNext: TButton;
294294 btnFirst: TButton;
295295 btnNew: TButton;
296296 edtPersonID: TEdit;
297297 edtSurname: TEdit;
298298 edtDOB: TEdit;
299299 Memo1: TMemo;
300300 procedure btnFirstClick(Sender: TObject);
301301 procedure btnNewClick(Sender: TObject);
302302 procedure btnNextClick(Sender: TObject);
303303 procedure btnTestClick(Sender: TObject);
304304 private
305305 { private declarations }
306306 conn : TMySQL50Connection;
307307 query : TSQLQuery;
308308 transaction : TSQLTransaction;
309309 procedure Display;
310310 public
311311 { public declarations }
312312 end;
313313 var
314314 Form1: TForm1;
315315 implementation
316316 { TForm1 }
317317 procedure TForm1.btnTestClick(Sender: TObject);
318318 var
319319 S: String;
320320 begin
321321 conn := TMySQL50Connection.Create(nil);
322322 query := TSQLQuery.Create(nil);
323323 transaction := TSQLTransaction.Create(nil);
324324 try
325325 try
326326 conn.HostName := '127.0.0.1';
327327 conn.UserName := 'root';
328328 conn.Password := '';
329329 conn.DatabaseName := 'test1';
330330 conn.Connected := True;
331331 conn.Transaction := transaction;
332332 query.DataBase := conn;
333333 //query.ParseSQL := true; //該行不必須,這是預設的方法
334334 //query.ReadOnly := false; //該行不必須,這是預設的方法
335335 query.SQL.Text := 'select * from tperson';
336336 query.Open;
337337
338338 query.Last;
339339 S := IntToStr(query.RecordCount) + #13#10;
340340 query.First;
341341
342342 while not query.EOF do
343343 begin
344344 S := S + query.FieldByName('surname').AsString + #13#10;
345345 query.Next;
346346 end;
347347 finally
348348 //query.Free;
349349 //conn.Free;
350350 end;
351351 except
352352 on E: Exception do
353353 ShowMessage(E.message);
354354 end;
355355 Memo1.Text:= S;
356356 end;
357357
358358 procedure TForm1.Display;
359359 begin
360360 edtPersonID.Text := query.FieldByName('personid').AsString;
361361 edtSurname.Text := query.FieldByName('surname').AsString;
362362 edtDOB.Text := query.FieldByName('dob').AsString;
363363 end;
364364
365365 procedure TForm1.btnFirstClick(Sender: TObject);
366366 begin
367367 query.First;
368368 Display;
369369 end;
370370
371371 procedure TForm1.btnNewClick(Sender: TObject);
372372 begin
373373 query.Append;
374374 query.FieldValues['personid'] := edtPersonID.Text;
375375 query.FieldValues['surname'] := edtSurname.Text;
376376 query.FieldValues['dob'] := edtDOB.Text;
377377 query.Post;
378378 query.ApplyUpdates; //套用更新
379379 //transaction.Commit; //該行不必須
380380 end;
381381
382382 procedure TForm1.btnNextClick(Sender: TObject);
383383 begin
384384 query.Next;
385385 Display;
386386 end;
387387
388388 initialization
389389 {$I unt_db.lrs}
390390 end.
391391
392392這是使用 TMySQL50Connection,TSQLQuery,TSQLTransaction,TDatasource 與 TDBGrid 元件的另一種片版本,可將他們直接拉到表單上:
393393
394394 unit unt_mysql2;
395395 {$mode objfpc}{$H+}
396396 interface
397397 uses
398398 Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,
399399 mysql50conn, sqldb, StdCtrls, db, DBGrids, DbCtrls;
400400 type
401401 { TForm1 }
402402 TForm1 = class(TForm)
403403 btnConnect: TButton;
404404 btnSave: TButton;
405405 btnNext: TButton;
406406 btnPrior: TButton;
407407 Datasource1: TDatasource;
408408 DBGrid1: TDBGrid;
409409 Memo1: TMemo;
410410 MySQL50Connection1: TMySQL50Connection;
411411 SQLQuery1: TSQLQuery;
412412 SQLTransaction1: TSQLTransaction;
413413 procedure btnConnectClick(Sender: TObject);
414414 procedure btnNextClick(Sender: TObject);
415415 procedure btnPriorClick(Sender: TObject);
416416 procedure btnSaveClick(Sender: TObject);
417417 procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
418418 procedure FormCreate(Sender: TObject);
419419 private
420420 { private declarations }
421421 public
422422 { public declarations }
423423 end;
424424 var
425425 Form1: TForm1;
426426 implementation
427427 { TForm1 }
428428
429429 procedure TForm1.FormCreate(Sender: TObject);
430430 begin
431431 //設定元件內容:
432432 //(可以從物件檢視器做到)
433433 MySQL50Connection1.HostName := '127.0.0.1';
434434 MySQL50Connection1.UserName := 'root';
435435 MySQL50Connection1.Password := '';
436436 MySQL50Connection1.DatabaseName := 'test1';
437437 MySQL50Connection1.Transaction := SQLTransaction1;
438438 //SQLQuery1.ParseSQL := true; //該行不必須,這是預設值
439439 //SQLQuery1.ReadOnly := false; //該行不必須,這是預設值
440440 SQLQuery1.SQL.Text := 'select * from tperson';
441441 SQLQuery1.Transaction := SQLTransaction1;
442442 SQLQuery1.UpdateMode := upWhereChanged;
443443 Datasource1.Dataset := SQLQuery1;
444444 DBGrid1.DataSource := Datasource1;;
445445 end;
446446
447447 procedure TForm1.btnConnectClick(Sender: TObject);
448448 var
449449 S : string;
450450 begin
451451 try
452452 MySQL50Connection1.Connected := true;
453453 SQLQuery1.Open;
454454
455455 //測試一下是否都 OK:
456456 SQLQuery1.Last;
457457 S := IntToStr(SQLQuery1.RecordCount) + #13#10;
458458 SQLQuery1.First;
459459 while not SQLQuery1.EOF do
460460 begin
461461 S := S + SQLQuery1.FieldByName('surname').AsString + #13#10;
462462 SQLQuery1.Next;
463463 end;
464464 except
465465 on E: Exception do
466466 ShowMessage(E.message);
467467 end;
468468 Memo1.Text:= S;
469469 end;
470470
471471 procedure TForm1.btnNextClick(Sender: TObject);
472472 begin
473473 SQLQuery1.Next;
474474 end;
475475
476476 procedure TForm1.btnPriorClick(Sender: TObject);
477477 begin
478478 SQLQuery1.Prior;
479479 end;
480480
481481 procedure TForm1.btnSaveClick(Sender: TObject);
482482 begin
483483 SQLQuery1.ApplyUpdates;
484484 end;
485485
486486 procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
487487 begin
488488 //必要的,或是在關閉時取得 EDatabase 錯誤:
489489 MySQL50Connection1.Connected := false;
490490 end;
491491
492492 initialization
493493 {$I unt_mysql2.lrs}
494494 end.
495495
496496## Lazarus 和 PostgreSQL
497497
498498這個教學很簡短,告訴大家如何在 Lazarus 0.9.12 或更新的版本下使用 TPQConnection 連線到 PostgreSQL 資料庫,本地端或遠端都行。
499499
500500在正確地安裝後,進行下列步驟:
501501
502502- 從 SQLdb 籤頁裡放入 PQConnection
503503- 從 SQLdb 籤頁裡放入 SQLQuery
504504- 從 SQLdb 籤頁裡放入 SQLTransaction
505505- 從資料存取 (DataAccess) 籤頁裡放入資料來源 (DataSource)
506506- 從資料控制 (DataControl) 籤頁裡放入 DBGrid
507507
508508- 在 PQConnection 裡填入:
509509 - 每個 SQLTransaction 物件的交易內容
510510 - 資料庫名稱
511511 - 主機名稱
512512 - 使用者名稱 + 密碼
513513
514514- 檢查 SQLTransaction 已自動改為指向 PQConnection
515515
516516- 在 SQLQuery 內填入:
517517 - 每個物件的交易內容
518518 - 每個物件的資料庫內容
519519 - SQL (像是 'select * from anytable' 這樣的句子)
520520
521521- 在資料庫來源物件內照著 SQLQuery 物件填入 DataSet 的內容
522522
523523- 在 DBGrid 內依資料庫來源物件填入資料來源
524524
525525將所有的物件都調為「已連線;connected」和「啟動;active」,DBGrid 應該還要填入設定好的時間。 TDBText 和 TDBEdit 看起來已經在運作,但(對我來說)他們只負責顯示資料。
526526
527527要變更資料庫內容,需要使用下列程式碼來呼叫資料庫引擎:
528528
529529` try`\
530530`   sql:= 'UPDATE table SET setting=1';`\
531531`   PQDataBase.Connected:=True;`\
532532`   PQDataBase.ExecuteDirect('開始作業;');`\
533533`   PQDataBase.ExecuteDirect(sql);`\
534534`   PQDataBase.ExecuteDirect('交付作業');`\
535535`   PQDataBase.Connected:=False;`\
536536` except`\
537537`   on E : EDatabaseError do`\
538538`     MemoLog.Append('資料庫錯誤:'+sql+chr(13)+chr(10)+E.ClassName+chr(13)+chr(10)+E.Message);`\
539539`   on E : Exception do`\
540540`     MemoLog.Append('錯誤'+sql+chr(13)+chr(10)+E.ClassName+chr(13)+chr(10)+E.Message);`\
541541` end;`
542542
543543- 備註:
544544 - 在 Windows 環境下測試,Lazarus 0.9.12 + PgSQL 8.3.1
545545 - Linux 環境下部份測試,Lazarus 0.9.12 and PgSQL 8.0.x
546546
547547- 安裝與錯誤:
548548 - 在測試版本 Lazarus .12下,欄位型態為「文字」與「數字」時會有程式錯誤
549549 - 在使用固定長度字元,整數與 8 位元浮點數時沒有問題
550550 - 有時候有些愚蠢的錯誤需要你重啟 Lazarus ...
551551 - 某些錯誤發生後,其交易仍在進行,而必須手動去關閉。
552552 - Lazarus 一些更新會讓交易在交付之前都無法看見
553553 - 內建的除錯器看起來也有些錯誤 (至少在 Windows 下時) - 有時候執行到 IDE 之外的會需要協助找尋錯誤
554554 - 在 Linux 下某些錯誤訊息只會出現在主控台下 -- 用主控台模式下指令來執行程式,有時候你會因此而得到一些額外的除錯訊息。
555555 - 錯誤:「無法載入 PostgreSQL 用戶端,libq.so 是否已安裝?」
556556 - 在 PostgreSQL 安裝時加入可以搜尋到 libpq* 的路徑。
557557 - 在 Linux 下,加入 libpq.so 檔案的路徑到你的函式庫 /etc/fpc.cfg 檔案裡,例如:-Fl/usr/local/pgsql/lib
558558 - 在 Windows 下,將這些函式庫路徑加入到環境變數 Path 裡,或是專案的目錄裡
559559 - 在 Windows 下,我將 C:\Program Files\PostgreSQL\8.1\bin 目錄下的 DLL 檔案都複製到另一個 PATH 變數裡的目錄。
560560 - 或是加入 postgres\bin 目錄到路徑裡
561561
562562## Lazarus 與 SQLite
563563
564564by Luiz Americo
565565
566566請至 [sqlite4fpc homepage](http://www.geocities.com/camara_luiz/) 取得 API reference 與更多的教材。
567567
568568### 前言
569569
570570TSqliteDataset 與 TSqlite3Dataset 繼承自 TDataset, 個自分別可存取 2.8.x 與 3.x.x sqlite 資料庫。 以下是使用Sqlite主要的優缺點:
571571
572572優點:
573573
574574- 靈活: 程式設計師可以選擇使用或不使用SQL 語言,允許他們使用SQL/sqlite容許的簡單的表格配置或是任何複雜的配置
575575- 自動更新資料庫: 不需要手動更新資料庫使用SQL 述?, 單一方法來照顧它
576576- 快速: 它的快取資料是放在記憶體, 使的瀏覽資料集是相當的快速
577577- 沒有伺服器的安裝/設定: 只是包裝在sqlite 動態函式庫
578578
579579缺點:
580580
581581- 要求外部的檔案 (sqlite 函式庫)
582582
583583### 需求
584584
585585- sqlite2 資料庫:
586586 - fpc 2.0.0
587587 - Lazarus 0.9.10
588588 - sqlite 執行期函式庫 2.8.15 或以上 (從 www.sqlite.org 獲得)
589589
590590- sqlite3 資料庫:
591591 - fpc 2.0.2
592592 - Lazarus 0.9.11 (svn 修訂版 8443 或以上)
593593 - sqlite 執行期函式庫 3.2.1 或以上 (從 www.sqlite.org 獲得)
594594
595595**開始一個 lazarus 專案前, 請先確認以下事項:**
596596
597597- SQLite 資料庫有在系統路徑 PATH 變數裡,或其它可執行的目錄
598598- 在 Linux 下,將 cmem 第一個放入主程式的 uses 語法內
599599 - 在 Debian,Ubuntu 和其他 Debian-like 發佈版本裡,為了要建置 Lazarus IDE 你得先安裝 libsqlite-dev/libsqlite3-dev 套件,而不僅只有 sqlite/sqlite3 (對 OpenSuSe 也一樣)
600600
601601### 使用方法 (基本)
602602
603603安裝 /components/sqlite 資料夾中的套件 (安裝教材[[Install Packages|在這裡]])
604604
605605於設計模式下設定以下屬性
606606
607607- FileName: sqlite 檔案的路徑 \[必要\]
608608- TableName: sql 語法中使用的表格(table)名稱 \[必要\]
609609- Sql: 一個 SQL 的 select 語法 \[非必要\]
610610
611611**建立一個資料表 (Dataset)**
612612
613613雙按元件圖示, 或點選右鍵選單中的「建立資料表」。便會出現一個簡單的表格編輯器。
614614
615615` 以下是 TSqliteDataset 與 TSqlite3Dataset 所支援的所有欄位格式:`
616616
617617` Integer`\
618618` AutoInc`\
619619` String`\
620620` Memo`\
621621` Bool `\
622622` Float`\
623623` Word`\
624624` DateTime`\
625625` Date`\
626626` Time`\
627627` LargeInt`\
628628` Currency`\
629629` `
630630
631631**取得資料**
632632
633633建立資料表後, 或者在已有的資料表。以 Open 方法開啟 dataset。 如果 SQL 屬性沒有設定內容, 則所有的資料與欄位都會被傳回, 效果與以下指令相同:
634634
635635` SQL:='Select * from TABLENAME'; `
636636
637637**為資料檔案套用更新**
638638
639639使用 ApplyUpdates 函式前,dataset 須包含至少一個主鍵欄位填入需求 (必須為唯一且非 NULL 值)
640640
641641這可以由兩種方式來達成:
642642
643643- 設定 PrimaryKey 屬性為主鍵欄位的名稱
644644- 新增一個 AutoInc 欄位(這比較簡單, 因為 TSqliteDataSet 會自行將此欄位當成主鍵)
645645
646646以上兩個條件設定好其中一個後, 只要呼叫以下指令
647647
648648` ApplyUpdates;`
649649
650650備註一:若兩個條件都有設定, 則欄位會使用 PrimaryKey 來更新資料
651651
652652備註二: 若 PrimaryKey 被指定的欄位不是主鍵, 則呼叫 ApplyUpdates 可能會造成資料的遺失, 所以請確定所選擇的欄位值是唯一且非 NULL 值。
653653
654654### 註記
655655
656656- 雖然此程式已經測試過 10000 筆的資料都運行的很好,TSqliteDataset 將所有的資料都留在記憶體裡,所以請記得只取出你所需要的資料就好 (特別是針對記事欄位)。
657657- 同一個資料檔案 (檔案的內容) 可以負責多個資料表/資料集合
658658- 數個資料集合 (不同的欄位合併後) 可以建立一個暫存的資料表
659659- SQL 允許你用 WHERE 的語法來篩選你要取出的資料,重覆開啟再關閉同一資料集合 (或是呼叫重新擷取資料 - RefetchData - 的方法)。但條件就是欄位的數量要一定
660660- 像使用一些複合的 SQL 敘述句,如 aliases,joins 同時檢視多個資料表 (請記得這麼做就是都分配在同一支資料檔案裡),但在 ApplyUpdates 的情況裡卻行不通。如果有人想要使用這種複合的查詢而又要套用更新到資料檔案,請寄信給我,我會告訴你一些絕竅
661661- 當為不是從 TSqliteDataset 建立的 sqlite2.x 資料檔妹設定檔案名稱時,雖然檔案可以開啟,但有些欄位可能無法正確地偵測到,會被當成是字串欄位。
662662
663663可以在 fpc/fcl/db/sqlite CVS 目錄下找到一個通用的範例
664664
665665Luiz Americo pascalive(at)bol(dot)com(dot)br
666666
667667## Lazarus 與 MSSQL
668668
669669需要啟用 Zeoslib (最新版修訂版),請見此頁下方的連結。
670670
671671## Lazarus and Interbase / Firebird
672672
673673請參看[[Install Packages|安裝套件]]。該頁為解釋如何連線到 IB 或 FB 主機的簡短範例。
674674
675675也可以使用最新的 Zeoslib 的版本 (取自 cvs)。
676676
677677### FBLib Firebird 函式庫
678678
679679\[<http://fblib.altervista.org/%7CFBLib%5D是一個不含資料感知元件的開放原始碼函式庫,使用> Borland Delphi,Freepascal 與 Lazarus 都可以直接對 Firebird 關聯資料庫做存取。
680680
681681現有的特點包括:
682682
683683- 直接對 Firebird 1.0.x 1.5.x Classic 或 SuperServer 版本做存取
684684- 跨平台工作 (Win32,Gnu/Linux,FreeBSD)
685685- 自動選取 'fbclient' 或 'gds32' 用戶端函式庫
686686- 支援參數查詢
687687- 支援 SQL 同源語 1/3
688688- LGPL 認證通過
689689- 解析前置檔頭資料
690690- 單一程式腳本解析
691691- EXE 末端僅只使用 100-150 KB
692692- 支援 BLOB 欄位
693693- SQL 腳本直接支援資料與 HTML 轉換
694694- 伺服器管理 (備份,還原,gfix...)
695695- 事件警告器
696696
697697你可以從 [FBLib's website](http://fblib.altervista.org/) 下載文件。
698698
699699## Lazarus and dBase
700700
701701Tony Maro
702702
703703You might also want to visit the beginnings of the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]]
704704
705705FPC includes a simple database component that is similar in function to the Delphi TTable component called "TDbf" ([TDbf Website](http://tdbf.sourceforge.net/)) 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 (Data Access tab).
706706
707707The 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.
708708
709709It's very easy to use. Simply 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.
710710
711711Real 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. Note: Current version of OpenOffice (2.0x) contains OpenOffice Base, which can create dbf files in a somewhat user-friendly way.
712712
713713Attempting to open a nonexistent table will generate an error. Tables can be created programmatically through the component after the runtime path and table name are set.
714714
715715For 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".
716716
717717In your code, insert the following:
718718
719719`   Dbf1.FilePathFull := '/path/to/my/database';`\
720720`   Dbf1.TableName := 'dvds';`\
721721`   With Dbf1.FieldDefs do begin`\
722722`       Add('Name', ftString, 80, True);`\
723723`       Add('Description', ftMemo, 0, False);`\
724724`       Add('Rating', ftString, 5, False);`\
725725`   end;`\
726726`   Dbf1.CreateTable;`
727727
728728When 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.
729729
730730Adding an index is a little different from your typical TTable. It must be done after the database is open. You use the same method also to rebuild the indices. For instance:
731731
732732`   Dbf1.Exclusive := True;`\
733733`   Dbf1.Open;`\
734734`   Dbf1.AddIndex('dvdsname','Name',[ixPrimary, ixUnique, ixCaseInsensitive]);`\
735735`   Dbf1.AddIndex('rating.ndx', 'Rating', [ixCaseInsensitive]);`\
736736`   Dbf1.Close;`
737737
738738The 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.
739739
740740I 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!
741741
742742### Searching and Displaying a data set
743743
744744Simon Batty
745745
746746In this example I wanted to search a database of books for all the titles an author has listed and then display the list in a memo box
747747
748748`   Dbf1.FilePathFull := '/home/somelocatio/database_location/'; // path to the database directory`\
749749`   Dbf1.TableName := 'books.dbase';                             // database file (including extension)`\
750750`   DbF1.Open;`\
751751`   memo1.Clear;                                                 // clear the memo box`
752752
753753`   Dbf1.FilterOptions := [foCaseInsensitive];`\
754754`   Df1.Filter := 'AU=' + QuotedStr('anauthor');         // AU is the field name containing the authors`
755755
756756`   Dbf1.Filtered := true;       // This selects the filtered set`\
757757`   Dbf1.First;                  // moves the the first filtered data`\
758758`   while not dbf1.EOF do        // prints the titles that match the author to the memo box`\
759759`   begin`\
760760`       memo1.Append(Dbf1.FieldByName('TI').AsString); // TI is the field name for titles`\
761761`       dbf1.next;                                     // use .next here NOT .findnext!`\
762762`   end;`\
763763`   Dbf1.Close;   `
764764
765765Note that you can use Ddf1.findfirst to get the first record in the filtered set, then use Dbf1.next to move though the data. I found that using Dbf1.Findnext just causes the program to hang.
766766
767767This database was generated using TurboBD that came with the Kylix 1. I cannot get TurboBD tables to work with Lazarus, however you can download a command line tool from TurboDB's website that allows you to convert TurboDB table to other formats.
768768
769769## Using TSdfDataset and TFixedDataset
770770
771771TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.
772772
773773To start with this formats, a initial database file should be created. The format is very simple, so use a text editor to do this.
774774
775775Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:
776776
777777 ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE
778778 1,resistor,resistor,1,1,1,LINE
779779 2,capacitor,capacitor,1,1,1,LINE
780780 3,transistor npn,transistor npn
781781
782782And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.
783783
784784 Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;
785785 Piet Pompies piet@pompies.net
786786
787787### Using the datasets directly
788788
789789Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:
790790
791791- The lines in the database can have a maximum size of about 300. A fix is being researched.
792792- It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file
793793- One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions
794794- The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like \# for example. So that when showing the data on screen all \# chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.
795795
796796``` pascal
797797constructor TComponentsDatabase.Create;
798798begin
799799 inherited Create;
800800
801801 FDataset := TSdfDataset.Create(nil);
802802 FDataset.FileName := vConfigurations.ComponentsDBFile;
803803
804804 // Not necessary with TSdfDataset
805805// FDataset.TableName := STR_DB_COMPONENTS_TABLE;
806806// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;
807807
808808 // Adds field definitions
809809 FDataset.FieldDefs.Add('ID', ftString);
810810 FDataset.FieldDefs.Add('NAMEEN', ftString);
811811 FDataset.FieldDefs.Add('NAMEPT', ftString);
812812 FDataset.FieldDefs.Add('HEIGHT', ftString);
813813 FDataset.FieldDefs.Add('WIDTH', ftString);
814814 FDataset.FieldDefs.Add('PINS', ftString);
815815 FDataset.FieldDefs.Add('DRAWINGCODE', ftString);
816816
817817 // Necessary for TSdfDataset
818818 FDataset.Delimiter := ',';
819819 FDataset.FirstLineAsSchema := True;
820820
821821 FDataset.Active := True;
822822
823823 // Sets the initial record
824824 CurrentRecNo := 1;
825825 FDataset.First;
826826end;
827827```
828828
829829When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo. If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1
830830
831831``` pascal
832832{@@
833833 Moves to the desired record using TDataset.Next and TDataset.Prior
834834 This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.
835835
836836 @param AID Indicates the record number. The first record has number 1
837837}
838838procedure TComponentsDatabase.GoToRec(AID: Integer);
839839begin
840840 // We are before the desired record, move forward
841841 if CurrentRecNo < AID then
842842 begin
843843 while (not FDataset.EOF) and (CurrentRecNo < AID) do
844844 begin
845845 FDataset.Next;
846846 FDataset.CursorPosChanged;
847847 Inc(CurrentRecNo);
848848 end;
849849 end
850850 // We are after the desired record, move back
851851 else if CurrentRecNo > AID then
852852 begin
853853 while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do
854854 begin
855855 FDataset.Prior;
856856 FDataset.CursorPosChanged;
857857 Dec(CurrentRecNo);
858858 end;
859859 end;
860860end;
861861```
862862
863863### 使用資料感知控制元件
864864
865865## 相關連結
866866
867867- [[Databases|在 Lazarus 下利用 DB-unit 建立資料庫應用程式]]\
868868- [[MySQLDatabases|使用 MySQL 建立資料庫應用程式]]\
869869- [[Zeos tutorial|使用 Zeos 元件建立資料庫應用程式]]
870870- [Pascal 資料物件集](http://pdo.sourceforge.net) 是為一資料庫 API,可在 FPC 下與 Delphi 下配合 MySQL 原始函式庫版 4.1 與 5.0,Firebird SQL 1.5 與 2.0 使用。這是來自 PHP PDO 類別的啟發。
871871
872872## 貢獻與變更
873873
874874本頁是從 epikwiki [version](http://lazarus-ccr.sourceforge.net/index.php?wiki=LazarusDatabase) 轉換過來的。
875875
876876---
877877*From the Free Pascal wiki, page "Lazarus Database Tutorial/zh TW", as it stood on 2020-02-18 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history