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

如何在Delphi 7中将MDB数据表内容写入INI文件?

将MDB数据表内容写入INI文件的解决方案

你的代码只写入一条数据,核心问题有几个:仅初始化一次数据、未移动记录指针、重复覆盖同一个INI键、仅固定写入3列。以下是修复并实现全量写入的方案:

现有代码的问题

  • 仅在循环外获取第一条记录的字段值,循环中始终复用该值
  • 未调用Adotable1.Next移动记录指针,全程停留在第一条记录
  • 重复写入同一个INI键(test1),后续内容会直接覆盖之前的
  • 仅固定拼接3列数据,未处理数据表的全部18列

改进后的代码(按记录分Section)

这种方案为每条记录创建独立的INI Section,结构更清晰易读:

procedure TForm1.Button4Click(Sender: TObject);
var
  ini: TIniFile;
  i, j: Integer;
  sRecordSection, sFieldValue: String;
begin
  Adotable1.First;
  ini := TIniFile.Create('C:\Users\win10_pro\Desktop\test.ini');
  try
    // 遍历数据表的每一条记录
    for i := 0 to Adotable1.RecordCount - 1 do
    begin
      // 为当前记录生成唯一的Section名称,如 [Record_1]、[Record_2]
      sRecordSection := Format('Record_%d', [i + 1]);
      // 遍历当前记录的所有字段(自动适配18列)
      for j := 0 to Adotable1.FieldCount - 1 do
      begin
        // 获取字段的字符串值
        sFieldValue := Adotable1.Fields[j].AsString;
        // 将字段名作为子键,写入对应Section
        ini.WriteString(sRecordSection, Adotable1.Fields[j].FieldName, sFieldValue);
      end;
      // 移动到下一条记录
      Adotable1.Next;
    end;
    ShowMessage('INI文件已生成');
  finally
    ini.Free;
  end;
end;

可选方案(所有记录在同一Section)

如果希望所有数据集中在一个Section下,可以用「记录编号+字段名」作为唯一键:

procedure TForm1.Button4Click(Sender: TObject);
var
  ini: TIniFile;
  i, j: Integer;
  sUniqueKey, sFieldValue: String;
begin
  Adotable1.First;
  ini := TIniFile.Create('C:\Users\win10_pro\Desktop\test.ini');
  try
    // 清空目标Section的原有内容(可选,避免旧数据残留)
    ini.EraseSection('AllTableData');
    // 遍历每条记录
    for i := 0 to Adotable1.RecordCount - 1 do
    begin
      // 遍历当前记录的所有字段
      for j := 0 to Adotable1.FieldCount - 1 do
      begin
        // 生成唯一键,如 Record1_name、Record2_capital
        sUniqueKey := Format('Record%d_%s', [i + 1, Adotable1.Fields[j].FieldName]);
        sFieldValue := Adotable1.Fields[j].AsString;
        ini.WriteString('AllTableData', sUniqueKey, sFieldValue);
      end;
      Adotable1.Next;
    end;
    ShowMessage('INI文件已生成');
  finally
    ini.Free;
  end;
end;

关键改进说明

  • 循环内调用Adotable1.Next,确保遍历数据表的所有10条记录
  • 自动遍历FieldCount适配18列,无需手动拼接字段名
  • 生成唯一的Section或键名,避免INI内容被覆盖
  • 结构清晰,后续读取INI文件时也能方便解析对应数据

内容的提问来源于stack exchange,提问作者손상희

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 10:30:31