Fuoco
2017-04-04 22:50:30 |
- 本篇介紹使用 SQLite 當作手機 Local 端資料儲存, Delphi 透過 FireDAC 與之傳遞資料
(Delphi 可透過 FireDAC 與各種資料庫直接溝通, 包括 InterBase, SQLite, MySQL, SQL Server, Oracle, PostgreSQL, IBM DB2, SQL Anywhere, Access, Firebird, Informix... 等, 是 Local 端的, 不用高興太早 orz), 更多官方的 SQLite+FireDAC 教學文件(英文)點這裡
- 首先新增一個 Multi-Device Application, 放置一個 TFDConnection 元件,
在元件上按右鍵, 選 Connection Editor, 第一項 Driver ID 選 SQLite, Database 按右邊瀏覽鍵, 選 C:\Users\Public\Documents\Embarcadero\Studio\18.0\Samples\Data\Employees.s3db 這是 Delphi 事先建立用來測試的資料庫, 然後按一下 Test 按鈕, 密瑪空白直接按 OK, 會顯示連線建立成功
 
- 然後將這個 TFDConnection 元件的屬性 Params.LockingMode 設為 lmNormal, LoginPrompt 設為 False, Connected 設為 True

- 用 LiveBindings 精靈來建立 LiveBindings 相關元件,
從功能表選 View > LiveBindings Designer -> 選 LiveBindings Wizard(仙女棒圖案)

選 Create a data source 按 Next
 選 FireDAC 按 Next
 Command Type 選 Query, Command Text 輸入 select Name, Department, Seniority from Employee order by Department (Command Text 即是輸入 SQL 指令, 可以按 Test Command 看語法有無錯誤) 按 Next 再按 Finish 完成, 此時 LiveBindings 已幫你建立兩個元件 TBindSourceDB 和 TFDQuery

- 再點一次 LiveBindings 精靈幫你建立 ListView 元件, 選 Link a control with a field 按 Next

選 TListView 按 Next

選 BindSourceDB1 按 Next

選 Name(員工姓名欄) 按 Next, 再按 Finish 完成, 此時會多出一個 TListView 元件

- 在 LiveBindings Designer 視窗中增加 TBindSourceDB 和 TListView 之間的關聯:
TListView 是要秀出來的"列表", 我們想將"員工名字"當作主要文字 在名字上方 Header 用小字秀出他的部門, 下方 Footer 秀出職稱 在 BindSourceDB1 的 Department(部門)點一下, 拖曳到 TListView 的 ItemHeader.Text 放開, 兩者之間自動多出一條連結

用同樣的方式將 Name(姓名) 連結到 Item.Text

點選 TListView 看它的屬性有一項 ItemAppearance 改為 ImageListItemRightButton Align 屬性改為 Client 擴展到最大, 回到 LiveBindings Designer 視窗中的 ListViewName 就會有 Item.ButtonText 再將 Seniority(職稱)與 Item.ButtonText 連起來

- 此外, FireDAC 運作還需要兩個元件 TFDGUIxWaitCursor 和 TFDPhysSQLiteDriverLink, 將它們新增到 Form 裡

- 由於資料庫在桌機硬碟裡, 在手機上執行時只能存取 internal storage 的資料(iOS 只能存取 StartUp\Documents\)
所以要再部屬(deploy)一下檔案位置, 並修改一些設定, 從功能表選 Project > Deployment 上方下拉選單要選 All Configuration - Android Platform (發佈到 Play 商店時才不用再 deploy 一次) 選 Add Files 然後選資料庫檔, 也就是 C:\Users\Public\Documents\Embarcadero\Studio\18.0\Samples\Data\Employees.s3db

然後點 Employees.s3db 再點上方 Change Remote Path for Selected Items 按鈕
 將它(Remote Path) 改為 assets\internal\ (iOS 的話改為 StartUp\Documents\)
 然後在 Platforms 欄位點一下, 再點右側[...], 確定只有 Android (iOS的話 就只要 iOS 那三項打勾) 不要勾 Win32, 因為不用 Copy 檔案到 Windows 平台


因為在手機上執行的時候, 資料庫位置改了, 所以要在程式裡告訴它 點 FDConnection1 元件, 然後在它的事件(Events) BeforeConnect 點兩下, 加入下列紅色這行 procedure TTabbedForm.FDConnection1BeforeConnect(Sender: TObject); begin FDConnection1.Params.Values['Database'] := TPath.Combine(TPath.GetDocumentsPath, 'Employees.s3db'); end; TPath 是在 System.IOUtils 中宣告的, 所以最前面 uses 要加入這一項 System.IOUtils apk 檔安裝時, 就會將這個資料庫放在手機上指定的位置 特別注意: 在 Deployment 視窗, 每個檔案最右邊還有一個 Overwrite 選項, 如果某些檔不希望在重新安裝時被蓋掉 可以改變此設定, 按鈕在改變 Remote Path 的按鈕右邊, Overwrite 屬性會在 Always/Never 之間切換 (Debug 和 Release 要分開改 Overwrite 屬性)  如此, 程式應該就可以執行了

|