Sign in Join
Wiki copytemporary

Lazarus Database Tutorial/zh TW: what changed

Revision 3 to 4. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
1+---
2+[[Portal:Databases|**Databases portal**]]
3+References: · [[Databases|General info]] · [[Database libraries|Libraries]] · [[Database field type|Field types]] · [[Data Controls tab|Controls]] · [[Lazarus DB Faq|FAQ]] · [[SqlDBHowto|SQL how-to]] · [[Working With TSQLQuery]] · [[How to write in-memory database applications in Lazarus/FPC|In-memory database applications]] · Tutorials/practical articles: · [[Lazarus Database Overview|Overview]] · [[SQLdb Tutorial0|0 - Database set-up]] · [[SQLdb Tutorial1|1 - Getting started]] · [[SQLdb Tutorial2|2 - Editing]] · [[SQLdb Tutorial3|3 - Queries]] · [[SQLdb Tutorial4|4 - Data modules]] · [[SQLdb Programming Reference]] · Databases · [[Advantage Database Server|Advantage]] \- [[MySQLDatabases|MySQL]] \- [[mssqlconn|MSSQL]] \- [[postgres|Postgres]] \- [[Firebird|Interbase]] \- [[Firebird]] \- [[Oracle]] \- [[ODBCConn|ODBC]] \- [[TParadox|Paradox]] \- [[SQLite]] \- [[Lazarus Tdbf Tutorial|dBASE]] \- [[MS Access]] \- [[Zeos tutorial|Zeos]]
4+
5+
16# Lazarus 資料庫教學
27
38## 導覽
49
5-本教材內容是關於如何於 Lazarus 下配合數種資料庫來工作。
10+本教材內容是關於如何於 Lazarus 下配合數種資料庫來工作。
611
7-Lazarus 支援數種非內建資料庫,而開發者仍應安裝各資料庫所對應的元件(Packages)。你可以透過程式碼或直接拉元件(components)至表單(from)來存取資料庫。資料感知 (data-aware) 元件代表資料庫欄位,並透過 TDataSource 設定指定的資料來源 (DataSource) 屬性物件來連接。資料來源代表一個資料表,是以連接至資料庫元件 (如:TPSQLDatabase, TSQLiteDataSet) 的 DataSet 屬性所選定的。資料感知元件位於「資料控制」籤頁內。資料來源及資料庫控制元件則位於「資料存取」的籤頁內。
12+Lazarus 支援數種非內建資料庫,而開發者仍應安裝各資料庫所對應的元件(Packages)。你可以透過程式碼或直接拉元件(components)至表單(from)來存取資料庫。資料感知 (data-aware) 元件代表資料庫欄位,並透過 TDataSource 設定指定的資料來源 (DataSource) 屬性物件來連接。資料來源代表一個資料表,是以連接至資料庫元件 (如:TPSQLDatabase, TSQLiteDataSet) 的 DataSet 屬性所選定的。資料感知元件位於「資料控制」籤頁內。資料來源及資料庫控制元件則位於「資料存取」的籤頁內。
813
914## Lazarus 與 MySQL
1015
1116### 讓 MySQL 在 Linux 或 Windows 中動起來
1217
13-照著 MySQL 使用手冊裡的指示,讓 mysqld 程序於背景執行。對於所有潛在的主機來源 (包含本機 'localhost',本機的名稱和其他透過網路連線的主機),所有的用戶 (包含根使用者,mysql,你自己和其他所有會用到的人) 都要設定使用權限。也要儘可能的達到安全性要求,所有使用者,包含根使用者都要有一個密碼。接著使用手冊上的範例方法來測試確定所有使用者在系統上的權限都安全可靠。
18+照著 MySQL 使用手冊裡的指示,讓 mysqld 程序於背景執行。對於所有潛在的主機來源 (包含本機 'localhost',本機的名稱和其他透過網路連線的主機),所有的用戶 (包含根使用者,mysql,你自己和其他所有會用到的人) 都要設定使用權限。也要儘可能的達到安全性要求,所有使用者,包含根使用者都要有一個密碼。接著使用手冊上的範例方法來測試確定所有使用者在系統上的權限都安全可靠。
1419
1520### 在文字模式中讓 MySQL 為 FPC 工作
1621
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 指令
18-
19-```text
22+在 $(fpc**src** 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 指令
23+```
2024CREATE DATABASE testdb;
2125```
2226
23-接著確認所有相關使用者擁有適當的存取權限
24-
25-```text
26-GRANT ALL ON testdb TO johnny-user IDENTIFIED BY 'johnnyspassword';
27+接著確認所有相關使用者擁有適當的存取權限
2728```
28-
29-現在你應試著去執行一個叫 mkdb 的指令碼:
29+GRANT ALL ON testdb TO johnny-user IDENTIFIED BY 'johnnyspassword';
30+```
3031
31-```text
32+現在你應試著去執行一個叫 mkdb 的指令碼:
33+```
3234sh ./mkdb
3335```
3436
35-這個指令應該會失敗, 因為系統不會允許匿名者存取資料庫。所以必須修改這個指令碼讓 mysql 讀取以下這行:
36-
37-```text
37+這個指令應該會失敗, 因為系統不會允許匿名者存取資料庫。所以必須修改這個指令碼讓 mysql 讀取以下這行:
38+```
3839mysql -u root -p ${1-testdb} << EOF >/dev/null
3940```
4041
41-接著試著再執行一次,系統提示要你輸入密碼。幸運的話你應該就可以管理剛建立的資料庫了。用以下的 mysql 指令測試一下(在 mysql 監視器中):
42-
43-```text
42+接著試著再執行一次,系統提示要你輸入密碼。幸運的話你應該就可以管理剛建立的資料庫了。用以下的 mysql 指令測試一下(在 mysql 監視器中):
43+```
4444select * from FPdev;
4545```
4646
47-即可看到一個列有 ID,使用者名稱和 Email 地址的FPC 開發者資料表了。
48-
49-現在可以執行測試程式 testdb.pp 了 (這檔也許還需要先編譯過,而且可能會在第一次編譯出錯!!)。
47+即可看到一個列有 ID,使用者名稱和 Email 地址的FPC 開發者資料表了。
5048
51-我找出這支程式可能無法連結 MySQL 的幾個原因:
49+現在可以執行測試程式 testdb.pp 了 (這檔也許還需要先編譯過,而且可能會在第一次編譯出錯!!)。
5250
53-- 我的系統 (SuSE Linux v9.0) 安裝的是 mysql v4.0.15,不同於安裝套件的版本 3。
51+我找出這支程式可能無法連結 MySQL 的幾個原因:
5452
55-- 程式需要輸入使用者和密碼來存取資料庫。
53+ * 我的系統 (SuSE Linux v9.0) 安裝的是 mysql v4.0.15,不同於安裝套件的版本 3。
5654
57-- 編譯器需要知道哪裡可以找到 MySQL 的函式庫 (**如果你並沒有安裝 MYSQL 的開發函式庫,那現在快裝!**)
55+ * 程式需要輸入使用者和密碼來存取資料庫。
5856
59-我將 testdb.pp 另存成 trydb.pp,然後做修改 - 這樣代表原來那支還是可以隨後透過 CVS 更新。 我另外也將在 mysql/ver40/ 子目錄下找到的那支另存成 mysql_v4.pp,mysql_com_v4.pp 和 mysql_version_v4.pp,記得你單元裡的程式也要改成適當的檔名。在 trydb.pp 裡我變更 uses 敘述句為
57+ * 編譯器需要知道哪裡可以找到 MySQL 的函式庫 (**如果你並沒有安裝 MYSQL 的開發函式庫,那現在快裝!**)
6058
61-``` pascal
59+我將 testdb.pp 另存成 trydb.pp,然後做修改 - 這樣代表原來那支還是可以隨後透過 CVS 更新。 我另外也將在 mysql/ver40/ 子目錄下找到的那支另存成 mysql_v4.pp,mysql_com_v4.pp 和 mysql_version_v4.pp,記得你單元裡的程式也要改成適當的檔名。在 trydb.pp 裡我變更 uses 敘述句為
60+```
6261uses mysql_v4
6362```
6463
65-mysql_v4.pp 的敘述句改為
66-
67-``` pascal
64+mysql_v4.pp 的敘述句改為
65+```
6866uses mysql_com_v4
6967```
7068
71-另外為要使用的函式庫加入一行到 /etc/fpc.cfg 裡:
72-
73-```text
69+另外為要使用的函式庫加入一行到 /etc/fpc.cfg 裡:
70+```
7471-Fl/lib;/usr/lib
7572```
7673
77-接下來的動作也許不必要做,因為你在安裝開發函式庫的時候應該會自動幫你建立連結,但檢查一下總是無仿。 進行前需要先找到我的 MYSQL 用戶端函式庫是放在 /usr/lib 目錄下面的哪裡,我的狀況是先下 shell 指令:
78-
79-```text
74+接下來的動作也許不必要做,因為你在安裝開發函式庫的時候應該會自動幫你建立連結,但檢查一下總是無仿。 進行前需要先找到我的 MYSQL 用戶端函式庫是放在 /usr/lib 目錄下面的哪裡,我的狀況是先下 shell 指令:
75+```
8076ln -s libmysqlclient.so.12.0.0 lmysqlclient
8177```
8278
83-建立一個軟連結讓 FPC 可以找的到函式庫。為了更準確一些我再建立一個連結
84-
85-```text
79+建立一個軟連結讓 FPC 可以找的到函式庫。為了更準確一些我再建立一個連結
80+```
8681ln -s libmysqlclient.so.12.0.0 mysqlclient
8782```
8883
89-然後放一個相同的連結在不同的其他目錄裡:不是必需,視請況而定! 然後有些使用者也許會需要增加如下的連結:
90-
91-```text
84+然後放一個相同的連結在不同的其他目錄裡:不是必需,視請況而定! 然後有些使用者也許會需要增加如下的連結:
85+```
9286ln -s libmysqlclient.so.12.0.0 libmysqlclient.so
9387```
9488
95-我修改 trydb.pp 的內容,含括進使用者連線資訊,從上到下計的內容有主機,使用者與密碼:
96-
97-``` pascal
89+我修改 trydb.pp 的內容,含括進使用者連線資訊,從上到下計的內容有主機,使用者與密碼:
90+```
9891const
99- host : Pchar= 'localhost';
100- user : Pchar= 'myusername';
101- passwd: Pchar = 'mypassword';
92+ host : Pchar= 'localhost';
93+ user : Pchar= 'myusername';
94+ passwd: Pchar = 'mypassword';
10295```
10396
104-我還發現我忽叫 mysql_connect() 還是無法連上 MySQL,但使用 mysql_real_connect() ,加上一堆參數後就可以了。未來還會更複雜,參數的數目似乎從 3 版(七個)換到 4 版(八個)還有變化。在使用 mysql_real_connect 之前我還得先使用 mysql_init(),但這在原始的 mysql.pp 裡並找不到,但出現於 mysql_v4.pp。
105-
106-所以連線的程式碼將會是現在這樣:
97+我還發現我忽叫 mysql_connect() 還是無法連上 MySQL,但使用 mysql_real_connect() ,加上一堆參數後就可以了。未來還會更複雜,參數的數目似乎從 3 版(七個)換到 4 版(八個)還有變化。在使用 mysql_real_connect 之前我還得先使用 mysql_init(),但這在原始的 mysql.pp 裡並找不到,但出現於 mysql_v4.pp。
10798
108-``` pascal
99+所以連線的程式碼將會是現在這樣:
100+```
109101{加一些額外的變數}
110-var
111- alloc : PMYSQL;
112-
113-{主程式片段}
114-
115-begin
116- if paramcount=1 then
117- begin
118- Dummy:=Paramstr(1)+#0;
119- DataBase:=@Dummy[1];
120- end;
121-
122-Writeln ('分派空間...');
123- alloc := mysql_init(PMYSQL(@qmysql));
124- Write ('連線到 MySQL...');
125- sock := mysql_real_connect(alloc, host, user, passwd, database, 0, nil, 0);
126- if sock=Nil then
127- begin
128- Writeln (stderr,'無法連線到 MySQL.');
129- Writeln (stderr, '錯誤是:', mysql_error(@qmysql));
130- halt(1);
131- end;
132- Writeln ('完成。');
133- Writeln ('連線資料:');
134-{$ifdef Unix}
135- writeln ('Mysql_port : ',mysql_port);
136- writeln ('Mysql_unix_port : ',mysql_unix_port);
137-{$endif}
138- writeln ('Host info : ',mysql_get_host_info(sock));
139- writeln ('Server info : ',mysql_stat(sock));
140- writeln ('Client info : ',mysql_get_client_info);
141-
142- Writeln ('選擇資料庫 ',DataBase,'...');
143- if mysql_select_db(sock,DataBase) < 0 then
144- begin
145- Writeln (stderr,'無法選取資料庫 ',Database);
146- Writeln (stderr,mysql_error(sock));
147- halt (1);
148- end;
149-{... 其他就如原來 testdb.pp 裡的內容}
102+ var
103+ alloc : PMYSQL;
104+
105+ {主程式片段}
106+
107+ begin
108+ if paramcount=1 then
109+ begin
110+ Dummy:=Paramstr(1)+#0;
111+ DataBase:=@Dummy[1];
112+ end;
113+
114+ Writeln ('分派空間...');
115+ alloc := mysql_init(PMYSQL(@qmysql));
116+ Write ('連線到 MySQL...');
117+ sock := mysql_real_connect(alloc, host, user, passwd, database, 0, nil, 0);
118+ if sock=Nil then
119+ begin
120+ Writeln (stderr,'無法連線到 MySQL.');
121+ Writeln (stderr, '錯誤是:', mysql_error(@qmysql));
122+ halt(1);
123+ end;
124+ Writeln ('完成。');
125+ Writeln ('連線資料:');
126+ {$ifdef Unix}
127+ writeln ('Mysql_port  : ',mysql_port);
128+ writeln ('Mysql_unix_port : ',mysql_unix_port);
129+ {$endif}
130+ writeln ('Host info  : ',mysql_get_host_info(sock));
131+ writeln ('Server info  : ',mysql_stat(sock));
132+ writeln ('Client info  : ',mysql_get_client_info);
133+
134+ Writeln ('選擇資料庫 ',DataBase,'...');
135+ if mysql_select_db(sock,DataBase) < 0 then
136+ begin
137+ Writeln (stderr,'無法選取資料庫 ',Database);
138+ Writeln (stderr,mysql_error(sock));
139+ halt (1);
140+ end;
141+ {... 其他就如原來 testdb.pp 裡的內容}
150142```
151143
152-現在 - 準備好開始編譯 trydb.pp 了嗎?
153-
154-```text
155- fpc trydb
144+
145+現在 - 準備好開始編譯 trydb.pp 了嗎?
156146```
157-
158-成功!現在執行:
147+fpc trydb
148+```
159149
160-```text
161- ./trydb
150+成功!現在執行:
162151```
152+./trydb
153+```
163154
164-哇!我讀取到 FPC 開發者的清單了!
155+哇!我讀取到 FPC 開發者的清單了!
165156
166-想要更精進的話:將使用者連線資訊的部份與 MySQL 的指令做成互動的模式,使用變數而不使用常數,如此可以在你退出 MySQL 前輸入多個 SQL 指令:參見[[Lazarus Database Tutorial/TryDbpp|所有程式一覽表]],當使用者資訊是從主控台模式輸入取得時,程式將要利用迴圈,讓 SQL 的指令可以重覆輸入 (可以不用分號做結尾),然後再將回應顯示出來,直到使用者鍵入 'quit' 為止。
157+想要更精進的話:將使用者連線資訊的部份與 MySQL 的指令做成互動的模式,使用變數而不使用常數,如此可以在你退出 MySQL 前輸入多個 SQL 指令:參見[[Lazarus Database Tutorial/TryDbpp|所有程式一覽表]],當使用者資訊是從主控台模式輸入取得時,程式將要利用迴圈,讓 SQL 的指令可以重覆輸入 (可以不用分號做結尾),然後再將回應顯示出來,直到使用者鍵入 'quit' 為止。
167158
168-參見[[Lazarus Database Tutorial/SampleListing|主控台範例一覽表]]。
159+參見[[Lazarus Database Tutorial/SampleListing|主控台範例一覽表]]。
169160
170161### 在 Lazarus 的應用程式裡連線到 MySQL
171162
172-此教學將示範 Lazarus 如何連線到 MySQL 資料庫,並執行一段簡單的查詢,僅止使用 Lazarus 基本的元件;它並沒有用到任何資料感知元件,但已可想像連線到資料庫其介面的原理。
173-
174-建立一個新的 Lazarus 專案:
163+此教學將示範 Lazarus 如何連線到 MySQL 資料庫,並執行一段簡單的查詢,僅止使用 Lazarus 基本的元件;它並沒有用到任何資料感知元件,但已可想像連線到資料庫其介面的原理。
175164
176-```text
165+建立一個新的 Lazarus 專案:
166+```
177167〔專案〕->〔新專案〕->〔應用程式〕
178168```
179169
180-將會自動產生出一份表單。
181-
182-先把表單拉大到約半個畫面的大小,然後將表單的標題改名為 'TryMySQL'。
170+將會自動產生出一份表單。
183171
184-從標準元件的籤頁裡放置三個編輯方框到表單的左上,然後緊接著其下各放一個標籤。將標籤的標題改為「主機」(還有 HostLabel,HostEdit),「使用者名稱」 (還有 UserLabel,UserEdit) 和「密碼」 (還有 PasswordLabel 和 PasswordEdit)。或是你可以使用附加籤頁裡的標籤編輯元件來取代。
172+先把表單拉大到約半個畫面的大小,然後將表單的標題改名為 'TryMySQL'。
185173
186-選取密碼編輯的方框,找到 PasswordChar 這個內容:將其改為 * 或是其他字元,這樣當你鍵入你的密碼時你的畫面就會重覆顯示你這個字元來取代你真正的密碼。然後確定 Text 內容裡的值皆是空的。
174+從標準元件的籤頁裡放置三個編輯方框到表單的左上,然後緊接著其下各放一個標籤。將標籤的標題改為「主機」(還有 HostLabel,HostEdit),「使用者名稱」 (還有 UserLabel,UserEdit) 和「密碼」 (還有 PasswordLabel 和 PasswordEdit)。或是你可以使用附加籤頁裡的標籤編輯元件來取代。
187175
188-然後現在再放置一個編輯方框和標籤到你表單的右上方。改變標籤成「輸入 SQL 命令」,並命名為 CommandEdit。
176+選取密碼編輯的方框,找到 PasswordChar 這個內容:將其改為 * 或是其他字元,這樣當你鍵入你的密碼時你的畫面就會重覆顯示你這個字元來取代你真正的密碼。然後確定 Text 內容裡的值皆是空的。
189177
190-表單上再放三個按鈕:兩個在左邊,編框框的下面,另一個在右邊,命令框的下面。
178+然後現在再放置一個編輯方框和標籤到你表單的右上方。改變標籤成「輸入 SQL 命令」,並命名為 CommandEdit。
191179
192-將左邊的按鈕標記為「連結到資料庫」(ConnectButton) 與「離開」(ExitButton),而右邊的那個記為「送出查尋」(QueryButton)。
180+表單上再放三個按鈕:兩個在左邊,編框框的下面,另一個在右邊,命令框的下面。
193181
194-再放一個大的記事框在右下,標名為「結果」(ResultMemo),把送下能利用的空間都填滿給它。找到它捲軸條(ScrollBars)的內容,選為 ssAutoBoth,這樣捲軸條就可以為出現的文字自動調整空間。然後文字換行 (WordWrap) 的內容設為真 (True)。
182+將左邊的按鈕標記為「連結到資料庫」(ConnectButton) 與「離開」(ExitButton),而右邊的那個記為「送出查尋」(QueryButton)。
195183
196-再放一個狀態列 (從共通控制項籤頁裡) 在表單的下面,然後將其單純的文字 (SimpleText) 內容裡設為 'TryMySQL'。
184+再放一個大的記事框在右下,標名為「結果」(ResultMemo),把送下能利用的空間都填滿給它。找到它捲軸條(ScrollBars)的內容,選為 ssAutoBoth,這樣捲軸條就可以為出現的文字自動調整空間。然後文字換行 (WordWrap) 的內容設為真 (True)。
197185
198-擷圖將顯示表單長這個樣子:[Mysql 範例擷圖](http://lazarus-ccr.sourceforge.net/kbdata/trymysqldb.png)
186+再放一個狀態列 (從共通控制項籤頁裡) 在表單的下面,然後將其單純的文字 (SimpleText) 內容裡設為 'TryMySQL'。
199187
200-現在我們要寫一些事件處理器。
188+擷圖將顯示表單長這個樣子:[Mysql 範例擷圖](<http://lazarus-ccr.sourceforge.net/kbdata/trymysqldb.png>)
201189
202-這三個編輯框是用來輸入主機名稱,使用者名稱和密碼用的。當這三個都已輸入滿足條件後,將按下連線的按鈕。因此這按鈕 OnCLick 在事件處理器裡就是將在處理上述文字模式的 FPC 程式裡做的事情。
190+現在我們要寫一些事件處理器。
203191
204-而資料庫回傳的訊息,現在就不能用 Pascal 的 write 和 writeln 這兩個敘述句來負責了:取而代之的是所有回應都將轉成字串然後丟到記事框裡。鑑於 Pascal 的 write 和 writeln 敘述句能「即時」地將資料型態轉換,因為在記事框要輸出的文字,在處理時也要能不含糊地都轉換成字串才送出,所以字元變數就要用 StrPass 轉換成字串變數,而數字就要用 IntToStr 去轉換。
192+這三個編輯框是用來輸入主機名稱,使用者名稱和密碼用的。當這三個都已輸入滿足條件後,將按下連線的按鈕。因此這按鈕 OnCLick 在事件處理器裡就是將在處理上述文字模式的 FPC 程式裡做的事情。
205193
206-在記事框裡顯示字串時將用
194+而資料庫回傳的訊息,現在就不能用 Pascal 的 write 和 writeln 這兩個敘述句來負責了:取而代之的是所有回應都將轉成字串然後丟到記事框裡。鑑於 Pascal 的 write 和 writeln 敘述句能「即時」地將資料型態轉換,因為在記事框要輸出的文字,在處理時也要能不含糊地都轉換成字串才送出,所以字元變數就要用 StrPass 轉換成字串變數,而數字就要用 IntToStr 去轉換。
207195
208-``` pascal
209-procedure ShowString (S : string);
210-(* display a string in a Memo box *)
211-begin
212- trymysqlForm1.ResultsMemo.Lines.Add (S)
213-end;
196+在記事框裡顯示字串時將用
214197```
215-
216-連線按鈕的事件處理器將會變成:
198+procedure ShowString (S : string);
199+ (* display a string in a Memo box *)
200+ begin
201+ trymysqlForm1.ResultsMemo.Lines.Add (S)
202+ end;
203+```
217204
218-``` pascal
205+連線按鈕的事件處理器將會變成:
206+```
219207procedure TtrymysqlForm1.ConnectButtonClick(Sender: TObject);
220-(* 使用主表單裡文字框裡輸入的使用者訊息來連線到 MySQL *)
221-var strg: string;
222-
223-begin
224-
225- dummy1 := trymysqlForm1.HostEdit.text+#0;
226- host := @dummy1[1];
227- dummy2 := trymysqlForm1.UserEdit.text+#0;
228- user := @dummy2[1] ;
229- dummy3 := trymysqlForm1.PasswdEdit.text+#0;
230- passwd := @dummy3[1] ;
208+ (* 使用主表單裡文字框裡輸入的使用者訊息來連線到 MySQL *)
209+ var strg: string;
210+
211+ begin
212+
213+ dummy1 := trymysqlForm1.HostEdit.text+#0;
214+ host := @dummy1[1];
215+ dummy2 := trymysqlForm1.UserEdit.text+#0;
216+ user := @dummy2[1] ;
217+ dummy3 := trymysqlForm1.PasswdEdit.text+#0;
218+ passwd := @dummy3[1] ;
231219```
232-
233-``` pascal
234- alloc := mysql_init(PMYSQL(@qmysql));
235- sock := mysql_real_connect(alloc, host, user, passwd, database, 0, nil, 0);
236- if sock=Nil then
237- begin
238- strg :='無法連線到 MySQL.'; showstring (strg);
239- Strg :='錯誤是:'+ StrPas(mysql_error(@qmysql)); showstring (strg);
240- end
241- else
242- begin
243- trymysqlForm1.statusBar1.simpletext := 'Connected to MySQL';
244- strg := '現在選擇資料庫:' + database; showstring (strg);
245-{$ifdef Unix}
246- strg :='Mysql_port : '+ IntToStr(mysql_port); showstring (strg);
247- strg :='Mysql_unix_port : ' + StrPas(mysql_unix_port); showstring (strg);
248-{$endif}
249- Strg :='Host info : ' + StrPas(mysql_get_host_info(sock));
250- showstring (strg);
251- Strg :='Server info : ' + StrPas(mysql_stat(sock)); showstring (strg);
252- Strg :='Client info : ' + Strpas(mysql_get_client_info); showstring (strg);
253-
254- trymysqlForm1.statusbar1.simpletext := '選取資料庫 ' + DataBase +' 中...';
255- if mysql_select_db(sock,DataBase) < 0 then
256- begin
257- strg :='無法選取資料庫 '+ Database; ShowString (strg);
258- Strg := mysql_error(sock); ShowString (strg);
259- end
260- end;
261-end;
262220```
263-
264-右方的文字框是用來輸入 SQL 語法的,不用在結尾加分號;當你輸入內容滿足語法條件是,按下送出查詢 (SendQuery) 按鈕,查詢即進行處理,然後結果都會寫進記事框 (ResultBox) 內。
265-
266-而送出查詢按鈕在事件處理器裡要做的事也跟先前在 FPC 文字模式裡寫的一樣,但除了在字串回傳後要丟上記事框內之前,其型態轉換不得含糊。
267-
268-這和文字模式的 FPC 程式唯一不一樣的地方在於當一但偵測到錯誤狀態時,程式不會中斷,MySQL 也不會關閉,取而代之的是事件處理又回到主表單,等待新的查詢再重新送出。程式只有在按下「離開」按鈕後,才會關閉 MySQL 的連線與整個應用程式。 送出查詢 (SendQuery) 按鈕的程式碼如下:
269-
270-``` pascal
271-procedure TtrymysqlForm1.QueryButtonClick(Sender: TObject);
272-var
273- dumquery, strg: string;
274-begin
275- dumquery := TrymysqlForm1.CommandEdit.text;
276- dumquery := dumquery+#0;
277- query := @dumquery[1];
278- trymysqlForm1.statusbar1.simpletext := '執行查詢中:'+ dumQuery +'...';
279- strg := '執行查詢中:' + dumQuery; showstring (strg);
280- if (mysql_query(sock,Query) < 0) then
281- begin
282- Strg :='查詢失敗 '+ StrPas(mysql_error(sock)); showstring (strg);
283- end
284- else
285- begin
286- recbuf := mysql_store_result(sock);
287- if RecBuf=Nil then
221+alloc := mysql_init(PMYSQL(@qmysql));
222+ sock := mysql_real_connect(alloc, host, user, passwd, database, 0, nil, 0);
223+ if sock=Nil then
288224 begin
289- Strg :='查詢回傳的內容為空。'; showstring (strg);
290- end
225+ strg :='無法連線到 MySQL.'; showstring (strg);
226+ Strg :='錯誤是:'+ StrPas(mysql_error(@qmysql)); showstring (strg);
227+ end
291228 else
292229 begin
293- strg :='回傳資料筆數:' + IntToStr(mysql_num_rows (recbuf));
294- Showstring (strg);
295- Strg :='欄位記錄數:' + IntToStr(mysql_num_fields(recbuf));
230+ trymysqlForm1.statusBar1.simpletext := 'Connected to MySQL';
231+ strg := '現在選擇資料庫:' + database; showstring (strg);
232+ {$ifdef Unix}
233+ strg :='Mysql_port  : '+ IntToStr(mysql_port); showstring (strg);
234+ strg :='Mysql_unix_port : ' + StrPas(mysql_unix_port); showstring (strg);
235+ {$endif}
236+ Strg :='Host info  : ' + StrPas(mysql_get_host_info(sock));
296237 showstring (strg);
297- rowbuf := mysql_fetch_row(recbuf);
298- while (rowbuf <>nil) do
238+ Strg :='Server info  : ' + StrPas(mysql_stat(sock)); showstring (strg);
239+ Strg :='Client info  : ' + Strpas(mysql_get_client_info); showstring (strg);
240+
241+ trymysqlForm1.statusbar1.simpletext := '選取資料庫 ' + DataBase +' 中...';
242+ if mysql_select_db(sock,DataBase) < 0 then
243+ begin
244+ strg :='無法選取資料庫 '+ Database; ShowString (strg);
245+ Strg := mysql_error(sock); ShowString (strg);
246+ end
247+ end;
248+ end;
249+```
250+
251+
252+右方的文字框是用來輸入 SQL 語法的,不用在結尾加分號;當你輸入內容滿足語法條件是,按下送出查詢 (SendQuery) 按鈕,查詢即進行處理,然後結果都會寫進記事框 (ResultBox) 內。
253+
254+而送出查詢按鈕在事件處理器裡要做的事也跟先前在 FPC 文字模式裡寫的一樣,但除了在字串回傳後要丟上記事框內之前,其型態轉換不得含糊。
255+
256+這和文字模式的 FPC 程式唯一不一樣的地方在於當一但偵測到錯誤狀態時,程式不會中斷,MySQL 也不會關閉,取而代之的是事件處理又回到主表單,等待新的查詢再重新送出。程式只有在按下「離開」按鈕後,才會關閉 MySQL 的連線與整個應用程式。 送出查詢 (SendQuery) 按鈕的程式碼如下:
257+```
258+procedure TtrymysqlForm1.QueryButtonClick(Sender: TObject);
259+ var
260+ dumquery, strg: string;
261+ begin
262+ dumquery := TrymysqlForm1.CommandEdit.text;
263+ dumquery := dumquery+#0;
264+ query := @dumquery[1];
265+ trymysqlForm1.statusbar1.simpletext := '執行查詢中:'+ dumQuery +'...';
266+ strg := '執行查詢中:' + dumQuery; showstring (strg);
267+ if (mysql_query(sock,Query) < 0) then
299268 begin
300- Strg :='(Id: '+ rowbuf[0]+', Name: ' + rowbuf[1]+ ', Email : ' +
301- rowbuf[2] +')';
302- showstring (strg);
303- rowbuf := mysql_fetch_row(recbuf);
269+ Strg :='查詢失敗 '+ StrPas(mysql_error(sock)); showstring (strg);
270+ end
271+ else
272+ begin
273+ recbuf := mysql_store_result(sock);
274+ if RecBuf=Nil then
275+ begin
276+ Strg :='查詢回傳的內容為空。'; showstring (strg);
277+ end
278+ else
279+ begin
280+ strg :='回傳資料筆數:' + IntToStr(mysql_num_rows (recbuf));
281+ Showstring (strg);
282+ Strg :='欄位記錄數:' + IntToStr(mysql_num_fields(recbuf));
283+ showstring (strg);
284+ rowbuf := mysql_fetch_row(recbuf);
285+ while (rowbuf <>nil) do
286+ begin
287+ Strg :='(Id: '+ rowbuf[0]+', Name: ' + rowbuf[1]+ ', Email : ' +
288+ rowbuf[2] +')';
289+ showstring (strg);
290+ rowbuf := mysql_fetch_row(recbuf);
291+ end;
292+ end;
304293 end;
305- end;
306- end;
307-end;
294+ end;
308295```
309296
310-儲存你的專案,然後按〔執行〕-\>〔執行〕
297+
298+儲存你的專案,然後按〔執行〕->〔執行〕
311299
312300#### 下載 MYSQL 原始碼
313301
314-所有程式的一覽表都可以在這裡取得:[範例程式碼](http://lazarus-ccr.sourceforge.net/kbdata/mysqldemo.tar.gz)
302+所有程式的一覽表都可以在這裡取得:[範例程式碼](<http://lazarus-ccr.sourceforge.net/kbdata/mysqldemo.tar.gz>)
315303
316304## 使用 TMySQL50Connection 元件的簡單 MySQL 示範
317305
318-這程式碼是一個簡單快速的示範 (在 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 兩個按鈕來切換觀看。
319-
320- unit unt_db;
306+這程式碼是一個簡單快速的示範 (在 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 兩個按鈕來切換觀看。
307+```
308+unit unt_db;
321309 //範例來源:
322310 //http://www.lazarus.freepascal.org/index.php?name=PNphpBB2&file=viewtopic&t=5761
323311 //來自論壇的 tpglemur
324312 {$mode objfpc}{$H+}
325313 interface
326314 uses
327315 Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,
328316 mysql50conn, sqldb, StdCtrls;
329317 type
330318 { TForm1 }
331319 TForm1 = class(TForm)
332320 btnTest: TButton;
333321 btnNext: TButton;
334322 btnFirst: TButton;
335323 btnNew: TButton;
336324 edtPersonID: TEdit;
337325 edtSurname: TEdit;
338326 edtDOB: TEdit;
339327 Memo1: TMemo;
340328 procedure btnFirstClick(Sender: TObject);
341329 procedure btnNewClick(Sender: TObject);
342330 procedure btnNextClick(Sender: TObject);
343331 procedure btnTestClick(Sender: TObject);
344332 private
345333 { private declarations }
346- conn : TMySQL50Connection;
347- query : TSQLQuery;
348- transaction : TSQLTransaction;
334+ conn : TMySQL50Connection;
335+ query : TSQLQuery;
336+ transaction : TSQLTransaction;
349337 procedure Display;
350338 public
351339 { public declarations }
352340 end;
353341 var
354342 Form1: TForm1;
355343 implementation
356344 { TForm1 }
357345 procedure TForm1.btnTestClick(Sender: TObject);
358346 var
359347 S: String;
360348 begin
361- conn := TMySQL50Connection.Create(nil);
362- query := TSQLQuery.Create(nil);
363- transaction := TSQLTransaction.Create(nil);
349+ conn := TMySQL50Connection.Create(nil);
350+ query := TSQLQuery.Create(nil);
351+ transaction := TSQLTransaction.Create(nil);
364352 try
365353 try
366- conn.HostName := '127.0.0.1';
367- conn.UserName := 'root';
368- conn.Password := '';
369- conn.DatabaseName := 'test1';
370- conn.Connected := True;
371- conn.Transaction := transaction;
372- query.DataBase := conn;
373- //query.ParseSQL := true; //該行不必須,這是預設的方法
374- //query.ReadOnly := false; //該行不必須,這是預設的方法
375- query.SQL.Text := 'select * from tperson';
354+ conn.HostName := '127.0.0.1';
355+ conn.UserName := 'root';
356+ conn.Password := '';
357+ conn.DatabaseName := 'test1';
358+ conn.Connected := True;
359+ conn.Transaction := transaction;
360+ query.DataBase := conn;
361+ //query.ParseSQL := true; //該行不必須,這是預設的方法
362+ //query.ReadOnly := false; //該行不必須,這是預設的方法
363+ query.SQL.Text := 'select * from tperson';
376364 query.Open;
377-
365+
378366 query.Last;
379- S := IntToStr(query.RecordCount) + #13#10;
367+ S := IntToStr(query.RecordCount) + #13#10;
380368 query.First;
381-
369+
382370 while not query.EOF do
383371 begin
384- S := S + query.FieldByName('surname').AsString + #13#10;
372+ S := S + query.FieldByName('surname').AsString + #13#10;
385373 query.Next;
386374 end;
387375 finally
388376 //query.Free;
389377 //conn.Free;
390378 end;
391379 except
392380 on E: Exception do
393381 ShowMessage(E.message);
394382 end;
395383 Memo1.Text:= S;
396384 end;
397-
385+
398386 procedure TForm1.Display;
399387 begin
400- edtPersonID.Text := query.FieldByName('personid').AsString;
401- edtSurname.Text := query.FieldByName('surname').AsString;
402- edtDOB.Text := query.FieldByName('dob').AsString;
388+ edtPersonID.Text := query.FieldByName('personid').AsString;
389+ edtSurname.Text := query.FieldByName('surname').AsString;
390+ edtDOB.Text := query.FieldByName('dob').AsString;
403391 end;
404-
392+
405393 procedure TForm1.btnFirstClick(Sender: TObject);
406394 begin
407395 query.First;
408396 Display;
409397 end;
410-
398+
411399 procedure TForm1.btnNewClick(Sender: TObject);
412400 begin
413401 query.Append;
414- query.FieldValues['personid'] := edtPersonID.Text;
415- query.FieldValues['surname'] := edtSurname.Text;
416- query.FieldValues['dob'] := edtDOB.Text;
402+ query.FieldValues['personid'] := edtPersonID.Text;
403+ query.FieldValues['surname'] := edtSurname.Text;
404+ query.FieldValues['dob'] := edtDOB.Text;
417405 query.Post;
418406 query.ApplyUpdates; //套用更新
419407 //transaction.Commit; //該行不必須
420408 end;
421-
409+
422410 procedure TForm1.btnNextClick(Sender: TObject);
423411 begin
424412 query.Next;
425413 Display;
426414 end;
427-
415+
428416 initialization
429417 {$I unt_db.lrs}
430418 end.
431-
432-這是使用 TMySQL50Connection,TSQLQuery,TSQLTransaction,TDatasource 與 TDBGrid 元件的另一種片版本,可將他們直接拉到表單上:
419+```
433420
434- unit unt_mysql2;
421+這是使用 TMySQL50Connection,TSQLQuery,TSQLTransaction,TDatasource 與 TDBGrid 元件的另一種片版本,可將他們直接拉到表單上:
422+```
423+unit unt_mysql2;
435424 {$mode objfpc}{$H+}
436425 interface
437426 uses
438427 Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,
439428 mysql50conn, sqldb, StdCtrls, db, DBGrids, DbCtrls;
440429 type
441430 { TForm1 }
442431 TForm1 = class(TForm)
443432 btnConnect: TButton;
444433 btnSave: TButton;
445434 btnNext: TButton;
446435 btnPrior: TButton;
447436 Datasource1: TDatasource;
448437 DBGrid1: TDBGrid;
449438 Memo1: TMemo;
450439 MySQL50Connection1: TMySQL50Connection;
451440 SQLQuery1: TSQLQuery;
452441 SQLTransaction1: TSQLTransaction;
453442 procedure btnConnectClick(Sender: TObject);
454443 procedure btnNextClick(Sender: TObject);
455444 procedure btnPriorClick(Sender: TObject);
456445 procedure btnSaveClick(Sender: TObject);
457446 procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
458447 procedure FormCreate(Sender: TObject);
459448 private
460449 { private declarations }
461450 public
462451 { public declarations }
463452 end;
464453 var
465454 Form1: TForm1;
466455 implementation
467456 { TForm1 }
468-
457+
469458 procedure TForm1.FormCreate(Sender: TObject);
470459 begin
471460 //設定元件內容:
472461 //(可以從物件檢視器做到)
473- MySQL50Connection1.HostName := '127.0.0.1';
474- MySQL50Connection1.UserName := 'root';
475- MySQL50Connection1.Password := '';
476- MySQL50Connection1.DatabaseName := 'test1';
477- MySQL50Connection1.Transaction := SQLTransaction1;
478- //SQLQuery1.ParseSQL := true; //該行不必須,這是預設值
479- //SQLQuery1.ReadOnly := false; //該行不必須,這是預設值
480- SQLQuery1.SQL.Text := 'select * from tperson';
481- SQLQuery1.Transaction := SQLTransaction1;
482- SQLQuery1.UpdateMode := upWhereChanged;
483- Datasource1.Dataset := SQLQuery1;
484- DBGrid1.DataSource := Datasource1;;
462+ MySQL50Connection1.HostName := '127.0.0.1';
463+ MySQL50Connection1.UserName := 'root';
464+ MySQL50Connection1.Password := '';
465+ MySQL50Connection1.DatabaseName := 'test1';
466+ MySQL50Connection1.Transaction := SQLTransaction1;
467+ //SQLQuery1.ParseSQL := true; //該行不必須,這是預設值
468+ //SQLQuery1.ReadOnly := false; //該行不必須,這是預設值
469+ SQLQuery1.SQL.Text := 'select * from tperson';
470+ SQLQuery1.Transaction := SQLTransaction1;
471+ SQLQuery1.UpdateMode := upWhereChanged;
472+ Datasource1.Dataset := SQLQuery1;
473+ DBGrid1.DataSource := Datasource1;;
485474 end;
486-
475+
487476 procedure TForm1.btnConnectClick(Sender: TObject);
488477 var
489- S : string;
478+ S : string;
490479 begin
491480 try
492- MySQL50Connection1.Connected := true;
481+ MySQL50Connection1.Connected := true;
493482 SQLQuery1.Open;
494-
483+
495484 //測試一下是否都 OK:
496485 SQLQuery1.Last;
497- S := IntToStr(SQLQuery1.RecordCount) + #13#10;
486+ S := IntToStr(SQLQuery1.RecordCount) + #13#10;
498487 SQLQuery1.First;
499488 while not SQLQuery1.EOF do
500489 begin
501- S := S + SQLQuery1.FieldByName('surname').AsString + #13#10;
490+ S := S + SQLQuery1.FieldByName('surname').AsString + #13#10;
502491 SQLQuery1.Next;
503492 end;
504493 except
505494 on E: Exception do
506495 ShowMessage(E.message);
507496 end;
508497 Memo1.Text:= S;
509498 end;
510-
499+
511500 procedure TForm1.btnNextClick(Sender: TObject);
512501 begin
513502 SQLQuery1.Next;
514503 end;
515-
504+
516505 procedure TForm1.btnPriorClick(Sender: TObject);
517506 begin
518507 SQLQuery1.Prior;
519508 end;
520-
509+
521510 procedure TForm1.btnSaveClick(Sender: TObject);
522511 begin
523512 SQLQuery1.ApplyUpdates;
524513 end;
525-
514+
526515 procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
527516 begin
528517 //必要的,或是在關閉時取得 EDatabase 錯誤:
529- MySQL50Connection1.Connected := false;
518+ MySQL50Connection1.Connected := false;
530519 end;
531-
520+
532521 initialization
533522 {$I unt_mysql2.lrs}
534523 end.
524+```
535525
536526## Lazarus 和 PostgreSQL
537527
538-這個教學很簡短,告訴大家如何在 Lazarus 0.9.12 或更新的版本下使用 TPQConnection 連線到 PostgreSQL 資料庫,本地端或遠端都行。
539-
540-在正確地安裝後,進行下列步驟:
528+這個教學很簡短,告訴大家如何在 Lazarus 0.9.12 或更新的版本下使用 TPQConnection 連線到 PostgreSQL 資料庫,本地端或遠端都行。
541529
542-- 從 SQLdb 籤頁裡放入 PQConnection
543-- 從 SQLdb 籤頁裡放入 SQLQuery
544-- 從 SQLdb 籤頁裡放入 SQLTransaction
545-- 從資料存取 (DataAccess) 籤頁裡放入資料來源 (DataSource)
546-- 從資料控制 (DataControl) 籤頁裡放入 DBGrid
530+在正確地安裝後,進行下列步驟:
547531
548-- 在 PQConnection 裡填入:
549- - 每個 SQLTransaction 物件的交易內容
550- - 資料庫名稱
551- - 主機名稱
552- - 使用者名稱 + 密碼
532+ * 從 SQLdb 籤頁裡放入 PQConnection
533+ * 從 SQLdb 籤頁裡放入 SQLQuery
534+ * 從 SQLdb 籤頁裡放入 SQLTransaction
535+ * 從資料存取 (DataAccess) 籤頁裡放入資料來源 (DataSource)
536+ * 從資料控制 (DataControl) 籤頁裡放入 DBGrid
553537
554-- 檢查 SQLTransaction 已自動改為指向 PQConnection
538+ * 在 PQConnection 裡填入:
539+ * 每個 SQLTransaction 物件的交易內容
540+ * 資料庫名稱
541+ * 主機名稱
542+ * 使用者名稱 + 密碼
555543
556-- 在 SQLQuery 內填入:
557- - 每個物件的交易內容
558- - 每個物件的資料庫內容
559- - SQL (像是 'select * from anytable' 這樣的句子)
544+ * 檢查 SQLTransaction 已自動改為指向 PQConnection
560545
561-- 在資料庫來源物件內照著 SQLQuery 物件填入 DataSet 的內容
546+ * 在 SQLQuery 內填入:
547+ * 每個物件的交易內容
548+ * 每個物件的資料庫內容
549+ * SQL (像是 'select * from anytable' 這樣的句子)
562550
563-- 在 DBGrid 內依資料庫來源物件填入資料來源
551+ * 在資料庫來源物件內照著 SQLQuery 物件填入 DataSet 的內容
564552
565-將所有的物件都調為「已連線;connected」和「啟動;active」,DBGrid 應該還要填入設定好的時間。 TDBText 和 TDBEdit 看起來已經在運作,但(對我來說)他們只負責顯示資料。
553+ * 在 DBGrid 內依資料庫來源物件填入資料來源
566554
567-要變更資料庫內容,需要使用下列程式碼來呼叫資料庫引擎:
555+將所有的物件都調為「已連線;connected」和「啟動;active」,DBGrid 應該還要填入設定好的時間。 TDBText 和 TDBEdit 看起來已經在運作,但(對我來說)他們只負責顯示資料。
568556
569-``` pascal
570- try
571- sql:= 'UPDATE table SET setting=1';
572- PQDataBase.Connected:=True;
573- PQDataBase.ExecuteDirect('開始作業;');
574- PQDataBase.ExecuteDirect(sql);
575- PQDataBase.ExecuteDirect('交付作業');
576- PQDataBase.Connected:=False;
577- except
578- on E : EDatabaseError do
579- MemoLog.Append('資料庫錯誤:'+sql+chr(13)+chr(10)+E.ClassName+chr(13)+chr(10)+E.Message);
580- on E : Exception do
581- MemoLog.Append('錯誤'+sql+chr(13)+chr(10)+E.ClassName+chr(13)+chr(10)+E.Message);
582- end;
557+要變更資料庫內容,需要使用下列程式碼來呼叫資料庫引擎:
583558```
559+try
560+ sql:= 'UPDATE table SET setting=1';
561+ PQDataBase.Connected:=True;
562+ PQDataBase.ExecuteDirect('開始作業;');
563+ PQDataBase.ExecuteDirect(sql);
564+ PQDataBase.ExecuteDirect('交付作業');
565+ PQDataBase.Connected:=False;
566+ except
567+ on E : EDatabaseError do
568+ MemoLog.Append('資料庫錯誤:'+sql+chr(13)+chr(10)+E.ClassName+chr(13)+chr(10)+E.Message);
569+ on E : Exception do
570+ MemoLog.Append('錯誤'+sql+chr(13)+chr(10)+E.ClassName+chr(13)+chr(10)+E.Message);
571+ end;
572+```
584573
585-- 備註:
586- - 在 Windows 環境下測試,Lazarus 0.9.12 + PgSQL 8.3.1
587- - Linux 環境下部份測試,Lazarus 0.9.12 and PgSQL 8.0.x
574+
588575
589-- 安裝與錯誤:
590- - 在測試版本 Lazarus .12下,欄位型態為「文字」與「數字」時會有程式錯誤
591- - 在使用固定長度字元,整數與 8 位元浮點數時沒有問題
592- - 有時候有些愚蠢的錯誤需要你重啟 Lazarus ...
593- - 某些錯誤發生後,其交易仍在進行,而必須手動去關閉。
594- - Lazarus 一些更新會讓交易在交付之前都無法看見
595- - 內建的除錯器看起來也有些錯誤 (至少在 Windows 下時) - 有時候執行到 IDE 之外的會需要協助找尋錯誤
596- - 在 Linux 下某些錯誤訊息只會出現在主控台下 -- 用主控台模式下指令來執行程式,有時候你會因此而得到一些額外的除錯訊息。
597- - 錯誤:「無法載入 PostgreSQL 用戶端,libq.so 是否已安裝?」
598- - 在 PostgreSQL 安裝時加入可以搜尋到 libpq* 的路徑。
599- - 在 Linux 下,加入 libpq.so 檔案的路徑到你的函式庫 /etc/fpc.cfg 檔案裡,例如:-Fl/usr/local/pgsql/lib
600- - 在 Windows 下,將這些函式庫路徑加入到環境變數 Path 裡,或是專案的目錄裡
601- - 在 Windows 下,我將 C:\Program Files\PostgreSQL\8.1\bin 目錄下的 DLL 檔案都複製到另一個 PATH 變數裡的目錄。
602- - 或是加入 postgres\bin 目錄到路徑裡
576+ * 備註:
577+ * 在 Windows 環境下測試,Lazarus 0.9.12 + PgSQL 8.3.1
578+ * Linux 環境下部份測試,Lazarus 0.9.12 and PgSQL 8.0.x
603579
580+
581+
582+ * 安裝與錯誤:
583+ * 在測試版本 Lazarus .12下,欄位型態為「文字」與「數字」時會有程式錯誤
584+ * 在使用固定長度字元,整數與 8 位元浮點數時沒有問題
585+ * 有時候有些愚蠢的錯誤需要你重啟 Lazarus ...
586+ * 某些錯誤發生後,其交易仍在進行,而必須手動去關閉。
587+ * Lazarus 一些更新會讓交易在交付之前都無法看見
588+ * 內建的除錯器看起來也有些錯誤 (至少在 Windows 下時) - 有時候執行到 IDE 之外的會需要協助找尋錯誤
589+ * 在 Linux 下某些錯誤訊息只會出現在主控台下 -- 用主控台模式下指令來執行程式,有時候你會因此而得到一些額外的除錯訊息。
590+ * 錯誤:「無法載入 PostgreSQL 用戶端,libq.so 是否已安裝?」
591+ * 在 PostgreSQL 安裝時加入可以搜尋到 libpq* 的路徑。
592+ * 在 Linux 下,加入 libpq.so 檔案的路徑到你的函式庫 /etc/fpc.cfg 檔案裡,例如:-Fl/usr/local/pgsql/lib
593+ * 在 Windows 下,將這些函式庫路徑加入到環境變數 Path 裡,或是專案的目錄裡
594+ * 在 Windows 下,我將 C:\Program Files\PostgreSQL\8.1\bin 目錄下的 DLL 檔案都複製到另一個 PATH 變數裡的目錄。
595+ * 或是加入 postgres\bin 目錄到路徑裡
596+
604597## Lazarus 與 SQLite
605598
606-by Luiz Americo
599+by Luiz Americo
607600
608-請至 [sqlite4fpc homepage](http://www.geocities.com/camara_luiz/) 取得 API reference 與更多的教材。
601+請至 [sqlite4fpc homepage](<http://www.geocities.com/camara_luiz/>) 取得 API reference 與更多的教材。
609602
610603### 前言
611604
612-TSqliteDataset 與 TSqlite3Dataset 繼承自 TDataset, 個自分別可存取 2.8.x 與 3.x.x sqlite 資料庫。 以下是使用Sqlite主要的優缺點:
605+TSqliteDataset 與 TSqlite3Dataset 繼承自 TDataset, 個自分別可存取 2.8.x 與 3.x.x sqlite 資料庫。 以下是使用Sqlite主要的優缺點:
613606
614-優點:
607+優點:
615608
616-- 靈活: 程式設計師可以選擇使用或不使用SQL 語言,允許他們使用SQL/sqlite容許的簡單的表格配置或是任何複雜的配置
617-- 自動更新資料庫: 不需要手動更新資料庫使用SQL 述?, 單一方法來照顧它
618-- 快速: 它的快取資料是放在記憶體, 使的瀏覽資料集是相當的快速
619-- 沒有伺服器的安裝/設定: 只是包裝在sqlite 動態函式庫
609+ * 靈活: 程式設計師可以選擇使用或不使用SQL 語言,允許他們使用SQL/sqlite容許的簡單的表格配置或是任何複雜的配置
610+ * 自動更新資料庫: 不需要手動更新資料庫使用SQL 述?, 單一方法來照顧它
611+ * 快速: 它的快取資料是放在記憶體, 使的瀏覽資料集是相當的快速
612+ * 沒有伺服器的安裝/設定: 只是包裝在sqlite 動態函式庫
620613
621-缺點:
614+缺點:
622615
623-- 要求外部的檔案 (sqlite 函式庫)
616+ * 要求外部的檔案 (sqlite 函式庫)
624617
625618### 需求
626619
627-- sqlite2 資料庫:
628- - fpc 2.0.0
629- - Lazarus 0.9.10
630- - sqlite 執行期函式庫 2.8.15 或以上 (從 www.sqlite.org 獲得)
620+ * sqlite2 資料庫:
621+ * fpc 2.0.0
622+ * Lazarus 0.9.10
623+ * sqlite 執行期函式庫 2.8.15 或以上 (從 www.sqlite.org 獲得)
631624
632-- sqlite3 資料庫:
633- - fpc 2.0.2
634- - Lazarus 0.9.11 (svn 修訂版 8443 或以上)
635- - sqlite 執行期函式庫 3.2.1 或以上 (從 www.sqlite.org 獲得)
625+ * sqlite3 資料庫:
626+ * fpc 2.0.2
627+ * Lazarus 0.9.11 (svn 修訂版 8443 或以上)
628+ * sqlite 執行期函式庫 3.2.1 或以上 (從 www.sqlite.org 獲得)
636629
637630**開始一個 lazarus 專案前, 請先確認以下事項:**
638631
639-- SQLite 資料庫有在系統路徑 PATH 變數裡,或其它可執行的目錄
640-- 在 Linux 下,將 cmem 第一個放入主程式的 uses 語法內
641- - 在 Debian,Ubuntu 和其他 Debian-like 發佈版本裡,為了要建置 Lazarus IDE 你得先安裝 libsqlite-dev/libsqlite3-dev 套件,而不僅只有 sqlite/sqlite3 (對 OpenSuSe 也一樣)
632+ * SQLite 資料庫有在系統路徑 PATH 變數裡,或其它可執行的目錄
633+ * 在 Linux 下,將 cmem 第一個放入主程式的 uses 語法內
634+ * 在 Debian,Ubuntu 和其他 Debian-like 發佈版本裡,為了要建置 Lazarus IDE 你得先安裝 libsqlite-dev/libsqlite3-dev 套件,而不僅只有 sqlite/sqlite3 (對 OpenSuSe 也一樣)
642635
643636### 使用方法 (基本)
644637
645-安裝 /components/sqlite 資料夾中的套件 (安裝教材[[Install Packages|在這裡]])
638+安裝 /components/sqlite 資料夾中的套件 (安裝教材[[Install Packages|在這裡]])
646639
647-於設計模式下設定以下屬性
640+於設計模式下設定以下屬性
648641
649-- FileName: sqlite 檔案的路徑 \[必要\]
650-- TableName: sql 語法中使用的表格(table)名稱 \[必要\]
651-- Sql: 一個 SQL 的 select 語法 \[非必要\]
642+ * FileName: sqlite 檔案的路徑 [必要]
643+ * TableName: sql 語法中使用的表格(table)名稱 [必要]
644+ * Sql: 一個 SQL 的 select 語法 [非必要]
652645
653646**建立一個資料表 (Dataset)**
654647
655-雙按元件圖示, 或點選右鍵選單中的「建立資料表」。便會出現一個簡單的表格編輯器。
656-
657-```text
658- 以下是 TSqliteDataset 與 TSqlite3Dataset 所支援的所有欄位格式:
648+雙按元件圖示, 或點選右鍵選單中的「建立資料表」。便會出現一個簡單的表格編輯器。
659649```
660-
661-```text
662- Integer
663- AutoInc
664- String
665- Memo
666- Bool
667- Float
668- Word
669- DateTime
670- Date
671- Time
672- LargeInt
673- Currency
650+以下是 TSqliteDataset 與 TSqlite3Dataset 所支援的所有欄位格式:
674651```
652+```
653+Integer
654+ AutoInc
655+ String
656+ Memo
657+ Bool
658+ Float
659+ Word
660+ DateTime
661+ Date
662+ Time
663+ LargeInt
664+ Currency
665+```
675666
676667**取得資料**
677668
678-建立資料表後, 或者在已有的資料表。以 Open 方法開啟 dataset。 如果 SQL 屬性沒有設定內容, 則所有的資料與欄位都會被傳回, 效果與以下指令相同:
679-
680-``` pascal
681- SQL:='Select * from TABLENAME';
669+建立資料表後, 或者在已有的資料表。以 Open 方法開啟 dataset。 如果 SQL 屬性沒有設定內容, 則所有的資料與欄位都會被傳回, 效果與以下指令相同:
682670```
671+SQL:='Select * from TABLENAME';
672+```
683673
684674**為資料檔案套用更新**
685675
686-使用 ApplyUpdates 函式前,dataset 須包含至少一個主鍵欄位填入需求 (必須為唯一且非 NULL 值)
687-
688-這可以由兩種方式來達成:
676+使用 ApplyUpdates 函式前,dataset 須包含至少一個主鍵欄位填入需求 (必須為唯一且非 NULL 值)
689677
690-- 設定 PrimaryKey 屬性為主鍵欄位的名稱
691-- 新增一個 AutoInc 欄位(這比較簡單, 因為 TSqliteDataSet 會自行將此欄位當成主鍵)
678+這可以由兩種方式來達成:
692679
693-以上兩個條件設定好其中一個後, 只要呼叫以下指令
680+ * 設定 PrimaryKey 屬性為主鍵欄位的名稱
681+ * 新增一個 AutoInc 欄位(這比較簡單, 因為 TSqliteDataSet 會自行將此欄位當成主鍵)
694682
695-```text
696- ApplyUpdates;
683+以上兩個條件設定好其中一個後, 只要呼叫以下指令
697684```
685+ApplyUpdates;
686+```
698687
699-備註一:若兩個條件都有設定, 則欄位會使用 PrimaryKey 來更新資料
688+備註一:若兩個條件都有設定, 則欄位會使用 PrimaryKey 來更新資料
700689
701-備註二: 若 PrimaryKey 被指定的欄位不是主鍵, 則呼叫 ApplyUpdates 可能會造成資料的遺失, 所以請確定所選擇的欄位值是唯一且非 NULL 值。
690+備註二: 若 PrimaryKey 被指定的欄位不是主鍵, 則呼叫 ApplyUpdates 可能會造成資料的遺失, 所以請確定所選擇的欄位值是唯一且非 NULL 值。
702691
703692### 註記
704693
705-- 雖然此程式已經測試過 10000 筆的資料都運行的很好,TSqliteDataset 將所有的資料都留在記憶體裡,所以請記得只取出你所需要的資料就好 (特別是針對記事欄位)。
706-- 同一個資料檔案 (檔案的內容) 可以負責多個資料表/資料集合
707-- 數個資料集合 (不同的欄位合併後) 可以建立一個暫存的資料表
708-- SQL 允許你用 WHERE 的語法來篩選你要取出的資料,重覆開啟再關閉同一資料集合 (或是呼叫重新擷取資料 - RefetchData - 的方法)。但條件就是欄位的數量要一定
709-- 像使用一些複合的 SQL 敘述句,如 aliases,joins 同時檢視多個資料表 (請記得這麼做就是都分配在同一支資料檔案裡),但在 ApplyUpdates 的情況裡卻行不通。如果有人想要使用這種複合的查詢而又要套用更新到資料檔案,請寄信給我,我會告訴你一些絕竅
710-- 當為不是從 TSqliteDataset 建立的 sqlite2.x 資料檔妹設定檔案名稱時,雖然檔案可以開啟,但有些欄位可能無法正確地偵測到,會被當成是字串欄位。
694+ * 雖然此程式已經測試過 10000 筆的資料都運行的很好,TSqliteDataset 將所有的資料都留在記憶體裡,所以請記得只取出你所需要的資料就好 (特別是針對記事欄位)。
695+ * 同一個資料檔案 (檔案的內容) 可以負責多個資料表/資料集合
696+ * 數個資料集合 (不同的欄位合併後) 可以建立一個暫存的資料表
697+ * SQL 允許你用 WHERE 的語法來篩選你要取出的資料,重覆開啟再關閉同一資料集合 (或是呼叫重新擷取資料 - RefetchData - 的方法)。但條件就是欄位的數量要一定
698+ * 像使用一些複合的 SQL 敘述句,如 aliases,joins 同時檢視多個資料表 (請記得這麼做就是都分配在同一支資料檔案裡),但在 ApplyUpdates 的情況裡卻行不通。如果有人想要使用這種複合的查詢而又要套用更新到資料檔案,請寄信給我,我會告訴你一些絕竅
699+ * 當為不是從 TSqliteDataset 建立的 sqlite2.x 資料檔妹設定檔案名稱時,雖然檔案可以開啟,但有些欄位可能無法正確地偵測到,會被當成是字串欄位。
711700
712-可以在 fpc/fcl/db/sqlite CVS 目錄下找到一個通用的範例
701+可以在 fpc/fcl/db/sqlite CVS 目錄下找到一個通用的範例
713702
714-Luiz Americo pascalive(at)bol(dot)com(dot)br
703+Luiz Americo pascalive(at)bol(dot)com(dot)br
715704
716705## Lazarus 與 MSSQL
717706
718-需要啟用 Zeoslib (最新版修訂版),請見此頁下方的連結。
707+需要啟用 Zeoslib (最新版修訂版),請見此頁下方的連結。
719708
720709## Lazarus and Interbase / Firebird
721710
722-請參看[[Install Packages|安裝套件]]。該頁為解釋如何連線到 IB 或 FB 主機的簡短範例。
711+請參看[[Install Packages|安裝套件]]。該頁為解釋如何連線到 IB 或 FB 主機的簡短範例。
723712
724-也可以使用最新的 Zeoslib 的版本 (取自 cvs)。
713+也可以使用最新的 Zeoslib 的版本 (取自 cvs)。
725714
726715### FBLib Firebird 函式庫
727716
728-\[<http://fblib.altervista.org/%7CFBLib%5D是一個不含資料感知元件的開放原始碼函式庫,使用> Borland Delphi,Freepascal 與 Lazarus 都可以直接對 Firebird 關聯資料庫做存取。
717+[[1]](<http://fblib.altervista.org/%7CFBLib>)是一個不含資料感知元件的開放原始碼函式庫,使用 Borland Delphi,Freepascal 與 Lazarus 都可以直接對 Firebird 關聯資料庫做存取。
729718
730-現有的特點包括:
719+現有的特點包括:
731720
732-- 直接對 Firebird 1.0.x 1.5.x Classic 或 SuperServer 版本做存取
733-- 跨平台工作 (Win32,Gnu/Linux,FreeBSD)
734-- 自動選取 'fbclient' 或 'gds32' 用戶端函式庫
735-- 支援參數查詢
736-- 支援 SQL 同源語 1/3
737-- LGPL 認證通過
738-- 解析前置檔頭資料
739-- 單一程式腳本解析
740-- EXE 末端僅只使用 100-150 KB
741-- 支援 BLOB 欄位
742-- SQL 腳本直接支援資料與 HTML 轉換
743-- 伺服器管理 (備份,還原,gfix...)
744-- 事件警告器
721+ * 直接對 Firebird 1.0.x 1.5.x Classic 或 SuperServer 版本做存取
722+ * 跨平台工作 (Win32,Gnu/Linux,FreeBSD)
723+ * 自動選取 'fbclient' 或 'gds32' 用戶端函式庫
724+ * 支援參數查詢
725+ * 支援 SQL 同源語 1/3
726+ * LGPL 認證通過
727+ * 解析前置檔頭資料
728+ * 單一程式腳本解析
729+ * EXE 末端僅只使用 100-150 KB
730+ * 支援 BLOB 欄位
731+ * SQL 腳本直接支援資料與 HTML 轉換
732+ * 伺服器管理 (備份,還原,gfix...)
733+ * 事件警告器
745734
746-你可以從 [FBLib's website](http://fblib.altervista.org/) 下載文件。
735+你可以從 [FBLib's website](<http://fblib.altervista.org/>) 下載文件。
747736
748737## Lazarus and dBase
749738
750-Tony Maro
739+[Tony Maro](</User:Tonymaro> "User:Tonymaro")
751740
752741You might also want to visit the beginnings of the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]]
753742
754-FPC 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).
755-
756-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.
743+FPC 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).
757744
758-It'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.
745+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.
759746
760-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. Note: Current version of OpenOffice (2.0x) contains OpenOffice Base, which can create dbf files in a somewhat user-friendly way.
747+It'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.
761748
762-Attempting 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.
749+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. Note: Current version of OpenOffice (2.0x) contains OpenOffice Base, which can create dbf files in a somewhat user-friendly way.
763750
764-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".
751+Attempting 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.
765752
766-In your code, insert the following:
753+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".
767754
768-``` pascal
769- Dbf1.FilePathFull := '/path/to/my/database';
770- Dbf1.TableName := 'dvds';
771- With Dbf1.FieldDefs do begin
772- Add('Name', ftString, 80, True);
773- Add('Description', ftMemo, 0, False);
774- Add('Rating', ftString, 5, False);
775- end;
776- Dbf1.CreateTable;
755+In your code, insert the following:
777756```
778-
779-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.
757+Dbf1.FilePathFull := '/path/to/my/database';
758+ Dbf1.TableName := 'dvds';
759+ With Dbf1.FieldDefs do begin
760+ Add('Name', ftString, 80, True);
761+ Add('Description', ftMemo, 0, False);
762+ Add('Rating', ftString, 5, False);
763+ end;
764+ Dbf1.CreateTable;
765+```
780766
781-Adding 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:
767+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.
782768
783-``` pascal
784- Dbf1.Exclusive := True;
785- Dbf1.Open;
786- Dbf1.AddIndex('dvdsname','Name',[ixPrimary, ixUnique, ixCaseInsensitive]);
787- Dbf1.AddIndex('rating.ndx', 'Rating', [ixCaseInsensitive]);
788- Dbf1.Close;
769+Adding 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:
789770```
771+Dbf1.Exclusive := True;
772+ Dbf1.Open;
773+ Dbf1.AddIndex('dvdsname','Name',[ixPrimary, ixUnique, ixCaseInsensitive]);
774+ Dbf1.AddIndex('rating.ndx', 'Rating', [ixCaseInsensitive]);
775+ Dbf1.Close;
776+```
790777
791-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.
778+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.
792779
793-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!
780+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!
794781
782+
783+
795784### Searching and Displaying a data set
796785
797-Simon Batty
786+[Simon Batty](</User:Svbfieldview.net> "User:Svbfieldview.net \(page does not exist\)")
798787
799-In 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
788+In 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
800789
801-``` pascal
802- Dbf1.FilePathFull := '/home/somelocatio/database_location/'; // path to the database directory
803- Dbf1.TableName := 'books.dbase'; // database file (including extension)
804- DbF1.Open;
805- memo1.Clear; // clear the memo box
806-```
790+
807791
808-``` pascal
809- Dbf1.FilterOptions := [foCaseInsensitive];
810- Df1.Filter := 'AU=' + QuotedStr('anauthor'); // AU is the field name containing the authors
811792```
812-
813-``` pascal
814- Dbf1.Filtered := true; // This selects the filtered set
815- Dbf1.First; // moves the the first filtered data
816- while not dbf1.EOF do // prints the titles that match the author to the memo box
817- begin
818- memo1.Append(Dbf1.FieldByName('TI').AsString); // TI is the field name for titles
819- dbf1.next; // use .next here NOT .findnext!
820- end;
821- Dbf1.Close;
793+Dbf1.FilePathFull := '/home/somelocatio/database_location/'; // path to the database directory
794+ Dbf1.TableName := 'books.dbase'; // database file (including extension)
795+ DbF1.Open;
796+ memo1.Clear; // clear the memo box
822797```
798+```
799+Dbf1.FilterOptions := [foCaseInsensitive];
800+ Df1.Filter := 'AU=' + QuotedStr('anauthor'); // AU is the field name containing the authors
801+```
802+```
803+Dbf1.Filtered := true; // This selects the filtered set
804+ Dbf1.First; // moves the the first filtered data
805+ while not dbf1.EOF do // prints the titles that match the author to the memo box
806+ begin
807+ memo1.Append(Dbf1.FieldByName('TI').AsString); // TI is the field name for titles
808+ dbf1.next; // use .next here NOT .findnext!
809+ end;
810+ Dbf1.Close;
811+```
823812
824-Note 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.
813+Note 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.
825814
826-This 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.
815+This 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.
827816
828817## Using TSdfDataset and TFixedDataset
829818
830-TSdfDataset 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.
831-
832-To start with this formats, a initial database file should be created. The format is very simple, so use a text editor to do this.
819+TSdfDataset 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.
833820
834-Bellow 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:
821+To start with this formats, a initial database file should be created. The format is very simple, so use a text editor to do this.
835822
836- ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE
823+Bellow 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:
824+```
825+ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE
837826 1,resistor,resistor,1,1,1,LINE
838827 2,capacitor,capacitor,1,1,1,LINE
839828 3,transistor npn,transistor npn
840-
841-And 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.
829+```
842830
843- Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;
844- Piet Pompies piet@pompies.net
831+And 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.
832+```
833+Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;
834+ Piet Pompies piet@pompies.net
835+```
845836
846837### Using the datasets directly
847838
848-Sometimes 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:
839+Sometimes 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:
849840
850-- The lines in the database can have a maximum size of about 300. A fix is being researched.
851-- It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file
852-- One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions
853-- 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.
841+ * The lines in the database can have a maximum size of about 300. A fix is being researched.
842+ * It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file
843+ * One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions
844+ * 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.
854845
855-``` pascal
846+```
856847constructor TComponentsDatabase.Create;
857-begin
858- inherited Create;
859-
860- FDataset := TSdfDataset.Create(nil);
861- FDataset.FileName := vConfigurations.ComponentsDBFile;
862-
863- // Not necessary with TSdfDataset
864-// FDataset.TableName := STR_DB_COMPONENTS_TABLE;
865-// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;
866-
867- // Adds field definitions
868- FDataset.FieldDefs.Add('ID', ftString);
869- FDataset.FieldDefs.Add('NAMEEN', ftString);
870- FDataset.FieldDefs.Add('NAMEPT', ftString);
871- FDataset.FieldDefs.Add('HEIGHT', ftString);
872- FDataset.FieldDefs.Add('WIDTH', ftString);
873- FDataset.FieldDefs.Add('PINS', ftString);
874- FDataset.FieldDefs.Add('DRAWINGCODE', ftString);
875-
876- // Necessary for TSdfDataset
877- FDataset.Delimiter := ',';
878- FDataset.FirstLineAsSchema := True;
879-
880- FDataset.Active := True;
881-
882- // Sets the initial record
883- CurrentRecNo := 1;
884- FDataset.First;
885-end;
848+ begin
849+ inherited Create;
850+
851+ FDataset := TSdfDataset.Create(nil);
852+ FDataset.FileName := vConfigurations.ComponentsDBFile;
853+
854+ // Not necessary with TSdfDataset
855+ // FDataset.TableName := STR_DB_COMPONENTS_TABLE;
856+ // FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;
857+
858+ // Adds field definitions
859+ FDataset.FieldDefs.Add('ID', ftString);
860+ FDataset.FieldDefs.Add('NAMEEN', ftString);
861+ FDataset.FieldDefs.Add('NAMEPT', ftString);
862+ FDataset.FieldDefs.Add('HEIGHT', ftString);
863+ FDataset.FieldDefs.Add('WIDTH', ftString);
864+ FDataset.FieldDefs.Add('PINS', ftString);
865+ FDataset.FieldDefs.Add('DRAWINGCODE', ftString);
866+
867+ // Necessary for TSdfDataset
868+ FDataset.Delimiter := ',';
869+ FDataset.FirstLineAsSchema := True;
870+
871+ FDataset.Active := True;
872+
873+ // Sets the initial record
874+ CurrentRecNo := 1;
875+ FDataset.First;
876+ end;
886877```
887878
888-When 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
889-
890-``` pascal
879+When 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
880+```
891881{@@
892- Moves to the desired record using TDataset.Next and TDataset.Prior
893- This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.
894-
895- @param AID Indicates the record number. The first record has number 1
896-}
897-procedure TComponentsDatabase.GoToRec(AID: Integer);
898-begin
899- // We are before the desired record, move forward
900- if CurrentRecNo < AID then
901- begin
902- while (not FDataset.EOF) and (CurrentRecNo < AID) do
903- begin
904- FDataset.Next;
905- FDataset.CursorPosChanged;
906- Inc(CurrentRecNo);
907- end;
908- end
909- // We are after the desired record, move back
910- else if CurrentRecNo > AID then
911- begin
912- while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do
882+ Moves to the desired record using TDataset.Next and TDataset.Prior
883+ This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.
884+
885+ @param AID Indicates the record number. The first record has number 1
886+ }
887+ procedure TComponentsDatabase.GoToRec(AID: Integer);
913888 begin
914- FDataset.Prior;
915- FDataset.CursorPosChanged;
916- Dec(CurrentRecNo);
889+ // We are before the desired record, move forward
890+ if CurrentRecNo < AID then
891+ begin
892+ while (not FDataset.EOF) and (CurrentRecNo < AID) do
893+ begin
894+ FDataset.Next;
895+ FDataset.CursorPosChanged;
896+ Inc(CurrentRecNo);
897+ end;
898+ end
899+ // We are after the desired record, move back
900+ else if CurrentRecNo > AID then
901+ begin
902+ while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do
903+ begin
904+ FDataset.Prior;
905+ FDataset.CursorPosChanged;
906+ Dec(CurrentRecNo);
907+ end;
908+ end;
917909 end;
918- end;
919-end;
920910```
921911
922912### 使用資料感知控制元件
923913
924914## 相關連結
925915
926-- [[Databases|在 Lazarus 下利用 DB-unit 建立資料庫應用程式]]\
927-- [[MySQLDatabases|使用 MySQL 建立資料庫應用程式]]\
928-- [[Zeos tutorial|使用 Zeos 元件建立資料庫應用程式]]
929-- [Pascal 資料物件集](http://pdo.sourceforge.net) 是為一資料庫 API,可在 FPC 下與 Delphi 下配合 MySQL 原始函式庫版 4.1 與 5.0,Firebird SQL 1.5 與 2.0 使用。這是來自 PHP PDO 類別的啟發。
916+ * [[Databases|在 Lazarus 下利用 DB-unit 建立資料庫應用程式]]
930917
918+ * [[MySQLDatabases|使用 MySQL 建立資料庫應用程式]]
919+
920+ * [[Zeos tutorial|使用 Zeos 元件建立資料庫應用程式]]
921+ * [Pascal 資料物件集](<http://pdo.sourceforge.net>) 是為一資料庫 API,可在 FPC 下與 Delphi 下配合 MySQL 原始函式庫版 4.1 與 5.0,Firebird SQL 1.5 與 2.0 使用。這是來自 PHP PDO 類別的啟發。
922+
931923## 貢獻與變更
932924
933-本頁是從 epikwiki [version](http://lazarus-ccr.sourceforge.net/index.php?wiki=LazarusDatabase) 轉換過來的。
925+本頁是從 epikwiki [version](<http://lazarus-ccr.sourceforge.net/index.php?wiki=LazarusDatabase>) 轉換過來的。
934926
935927---
936-*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).*
928+*From the Free Pascal wiki, page "Lazarus Database Tutorial/zh TW", as the Internet Archive kept it on 2026-02-11, last changed on 2020-02-19. 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