You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Lazarus中配置SQLite数据库的相对文件路径(跨平台)

解决Lazarus中SQLite数据库的相对路径配置问题

简便的原生实现方案

Lazarus/FPC自带跨平台路径处理能力,无需复杂操作就能实现相对路径效果,步骤如下:

  1. 获取程序运行目录:用ExtractFilePath(ParamStr(0)),ParamStr(0)返回当前程序的完整路径,ExtractFilePath提取其中的目录部分,自动适配Windows(\)和macOS(/)的路径分隔符。
  2. 拼接数据库路径:将程序目录与数据库文件名(或子目录下的文件名)拼接,生成绝对路径。
  3. 赋值给SQLite组件:把拼接好的路径直接赋值给TSQLite3Connection的DatabaseName属性。

代码示例

procedure TMainForm.FormCreate(Sender: TObject);
var
  DBPath: string;
begin
  // 获取程序所在目录
  DBPath := ExtractFilePath(ParamStr(0));
  // 拼接数据库文件路径(示例:数据库在程序同目录下,文件名为crm.db)
  DBPath := DBPath + 'crm.db';
  // 若数据库在子目录(比如data文件夹),可改为:
  // DBPath := DBPath + 'data/crm.db';
  
  // 设置SQLite连接的数据库路径并打开连接
  SQLite3Connection1.DatabaseName := DBPath;
  SQLite3Connection1.Connected := True;
end;

该方案完全基于Lazarus/FPC原生函数,无额外依赖,跨平台兼容性好,代码简洁易维护。

调用Python转换路径的备选方案

虽然原生方案已足够解决问题,但如果确实需要通过Python实现路径转换,可参考以下方式:

实现思路

通过TProcess组件调用Python脚本,利用Python的os.path.abspath()函数将相对路径转为绝对路径,再读取返回结果赋值给SQLite组件。

代码示例

function GetAbsolutePathByPython(const RelativePath: string): string;
var
  Process: TProcess;
  Output: TStringList;
  PythonCmd: string;
begin
  Result := '';
  // 适配不同系统的Python命令:Windows用python,macOS用python3
  {$IFDEF MSWINDOWS}
    PythonCmd := 'python';
  {$ELSE}
    PythonCmd := 'python3';
  {$ENDIF}

  Process := TProcess.Create(nil);
  Output := TStringList.Create;
  try
    // 构造Python命令,传入相对路径并返回绝对路径
    Process.CommandLine := Format('%s -c "import os; print(os.path.abspath(''%s''))"', 
                                 [PythonCmd, RelativePath]);
    // 配置进程选项:等待执行完毕并启用管道输出
    Process.Options := [poWaitOnExit, poUsePipes];
    Process.Execute;

    // 读取Python输出的绝对路径
    Output.LoadFromStream(Process.Output);
    if Output.Count > 0 then
      Result := Trim(Output[0]);
  finally
    Process.Free;
    Output.Free;
  end;
end;

// 使用示例
procedure TMainForm.FormCreate(Sender: TObject);
var
  DBPath: string;
begin
  DBPath := GetAbsolutePathByPython('crm.db');
  if DBPath <> '' then
  begin
    SQLite3Connection1.DatabaseName := DBPath;
    SQLite3Connection1.Connected := True;
  end;
end;

注意事项

  • 需确保目标系统已安装Python,若要便携发布,需附带Python运行环境,会增加程序体积。
  • 代码通过条件编译适配了Windows和macOS的Python命令差异。

内容的提问来源于stack exchange,提问作者James McIntyre

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 20:57:58