目錄
1 下載lazarus
2 下載sqlite3源碼編譯生成庫文件
3 新建項目
4 設置并編譯
一次極簡單的測試,記錄一下。
操作系統:統信UOS,
內核:4.19.0-arm64-desktop
處理器:D3000
整個流程難點是生成so庫文件并正確加載。從別的地方復制過來的so文件都不行,反復加載測試都失敗。
以下是操作步驟:
1 下載lazarus
使用秋風定制的lazarus,全面支持常用操作系統,常見國產CPU。自己寫的FPC/Lazarus安裝程序(2025-06-24 v0.5.9.0下載) - 秋·風 - 博客園
安裝說明非常詳細,按照說明完成編譯安裝。
2 下載sqlite3源碼編譯生成庫文件
SQLite Download Page
下載了?sqlite-amalgamation-3500100,編譯生成?libsqlite3.so
建一個存放編譯生成程序的文件夾,例如數據盤中,bin/
上面的so文件保存在 bin/sys/?
3 新建項目
窗體很簡單,form中只有一個按鈕。
代碼:
unit Unit1;{$mode objfpc}{$H+}interfaceusesClasses, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls,SQLite3Conn, SQLDB, dynlibs, sqlite3dyn;type{ TForm1 }TForm1 = class(TForm)Button1: TButton;procedure Button1Click(Sender: TObject);privateprocedure ConnectDB;publicend;varForm1: TForm1;implementation{$R *.lfm}procedure TForm1.Button1Click(Sender: TObject);
beginConnectDB;
end;procedure TForm1.ConnectDB;
varConn: TSQLite3Connection;Trans: TSQLTransaction;DBPath, LibPath, LibName: String;xOK:Integer;
begin// 1. 確定庫文件名{$IFDEF WINDOWS}LibName := 'sqlite3.dll';{$ENDIF}{$IFDEF LINUX}LibName := 'libsqlite3.so';{$ENDIF}{$IFDEF DARWIN}LibName := 'libsqlite3.dylib';{$ENDIF}// 2. 構建庫文件路徑LibPath := ConcatPaths([ExtractFilePath(ParamStr(0)),'sys',LibName]);// 3. 驗證庫文件是否存在if not FileExists(LibPath) thenbeginShowMessage('SQLite 庫文件不存在:' + LineEnding + LibPath);Exit;end;// 4. 加載庫文件xOK:=sqlite3dyn.InitializeSqlite(LibPath);if xOK=0 thenbeginshowmessage('ERROR: ' + LibName +' NOT Loaded');exit;end elsebeginshowmessage( LibName + ' Loaded OK');end;// 5. 構建數據庫路徑DBPath := ConcatPaths([ExtractFilePath(ParamStr(0)),'data','test.db']);// 6. 確保目錄存在if not DirectoryExists(ExtractFilePath(DBPath)) thenif not ForceDirectories(ExtractFilePath(DBPath)) thenbeginShowMessage('無法創建目錄: ' + ExtractFilePath(DBPath));Exit;end;// 7. 創建數據庫對象Conn := TSQLite3Connection.Create(nil);Trans := TSQLTransaction.Create(nil);Conn.Transaction := Trans;try// 8. 設置數據庫路徑Conn.DatabaseName := DBPath;// 9. 處理新數據庫創建if not FileExists(DBPath) thenbegintryConn.Open;Conn.ExecuteDirect('CREATE TABLE IF NOT EXISTS Test (id INTEGER PRIMARY KEY, name TEXT)');Trans.Commit;Conn.Close;ShowMessage('新建數據庫: ' + DBPath);excepton E: Exception doShowMessage('創建數據庫失敗: ' + E.Message);end;end;// 10. 連接數據庫tryConn.Open;Trans.Active := True;if Conn.Connected thenShowMessage('數據庫連接成功!' + LineEnding +'路徑: ' + DBPath + LineEnding)elseShowMessage('連接失敗');excepton E: Exception doShowMessage('數據庫連接錯誤: ' + E.Message + LineEnding +'請檢查文件權限: ' + DBPath);end;finallyConn.Free;Trans.Free;end;
end;end.
4 設置并編譯
設置輸出路徑到前面建立的目錄。
然后編譯。
運行試試: