使用 Delphi 将 dbf 文件的记录插入到 MS Access 数据库中的表中

问题描述

我正在尝试将 dbf 文件的记录插入到我已经创建的 MS Access 数据库中的表中。

dbf 文件名称tab1.dbf,它包含三列:cl1,cl2,cl3

MS Access 数据库名称db1,它有一个tb2,包含三列:cl1,cl3

我已使用 ADOConnection1 将 Delphi 连接到 MS Access 数据库

要插入 dbf 文件的记录,我必须使用 OpenDialog1 在 Button1 中单击

我使用的代码是这样的:

procedure TForm1.Button1Click(Sender: TObject);
var importdir,ipo : string;

begin
if form1.OpenDialog1.Execute then
begin
importdir:= extractfiledir(form1.OpenDialog1.FileName);
ipo:= form1.OpenDialog1.FileName ;
end;
form1.Edit1.Text:= importdir;
ADOConnection1.Execute('insert into tab2 SELECT * FROM [ database = '+ipo+' ].tab1'  );
end;

但是当我执行 form1 时,我收到此错误消息: 文件名不正确

你们能帮我吗?

解决方法

下面是一个简单的解决方案。这很简单,因为它假定 Access 数据库结构与 dBASE 结构相同。您将从这个示例开始,以适应您的需求。

procedure TDbfToAccessWithAdoForm.DbfToAccessButtonClick(Sender: TObject);
var
    Fld       : Integer;
    FldValue  : Variant;
    InsertSQL : String;
begin
    ADOConnectionAccess.Connected := TRUE;
    ADOConnectionDbf.Connected    := TRUE;
    ADOQueryDbf.SQL.Text          := 'Select * from Clients';
    ADOQueryDbf.Open;

    // Build the parametrized INSERT statement
    InsertSQL := 'insert into Clients(';
    for Fld := 0 to ADOQueryDbf.FieldCount - 1 do
        InsertSQL := InsertSQL + ADOQueryDbf.Fields[Fld].FieldName + ',';
    // Remove extra coma
    Delete(InsertSQL,Length(InsertSQL),1);
    InsertSQL := InsertSQL + ') values (';
    for Fld := 0 to ADOQueryDbf.FieldCount - 1 do
        InsertSQL := InsertSQL + ':' + ADOQueryDbf.Fields[Fld].FieldName + ',1);
    InsertSQL := InsertSQL + ')';

    while not ADOQueryDbf.Eof do begin
        ADOQueryAccess.SQL.Text := InsertSQL;
        for Fld := 0 to ADOQueryDbf.FieldCount - 1 do begin
            FldValue := ADOQueryDbf.Fields[Fld].Value;
            // Here you can do whatever conversion is required
            if FldValue = Null then begin
                if ADOQueryDbf.FieldDefList[Fld].DataType = ftDateTime then
                    FldValue := 0      // My Access table doesn't like empty datetime
                else
                    FldValue := ' ';   // My Access table doesn't like empty string
            end;
            ADOQueryAccess.Parameters.ParamByName(ADOQueryDbf.Fields[Fld].FieldName).Value := FldValue;
        end;
        ADOQueryAccess.ExecSQL;
        ADOQueryDbf.Next;
    end;

    ADOQueryDbf.Close;
    ADOQueryAccess.Close;
end;

您应该添加错误检查和 try/finally 或 try/except。我让你照常做。