在统信UOS(Linux)中构建SQLite3桌面应用笔记
目录
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 设置并编译
设置输出路径到前面建立的目录。
然后编译。
运行试试: