创建 Access 数据库 mdb 数据库(delphi)

 


function CreateAccessDB(MDBFile: string): Boolean;

  function CreateAccessFile(FileName: String; PassWord: string=''): boolean;
  var
    vCatalog: OleVariant;
  begin
    Result := False;
    if FileExists(FileName) then begin
      gLastError := '表"'+ FileName + '"已经存在.';
      Exit;
    end;
    try
      vCatalog := CreateOleObject('ADOX.Catalog');
      vCatalog.Create(format(MDBConnectionString, [FileName, PassWord]));
      Result := True;
    except
      on E: Exception do gLastError := E.Message;
    end;
  end;

  function CreateFieldTable(TableName: string): boolean;
  var
    ADOCon: TADOConnection;
    AdoQry: TADOQuery;
    TblLst: TStringList;
    idx: Integer;
  begin
    Result := False;
    ADOCon := TADOConnection.Create(nil);
    ADOCon.ConnectionString := format(MDBConnectionString, [MDBFile, '']);
    ADOCon.LoginPrompt := False;
    AdoQry := TADOQuery.Create(nil);
    TblLst := TStringList.Create;
    try
      try
        ADOCon.Connected := True;
        ADOCon.GetTableNames(TblLst);

        if TblLst.Find('Tab1', idx) then begin
          gLastError := '表' + 'Tab1' + '已经存在!';
          Exit;
        end else begin
          AdoQry.Connection := ADOCon;
          AdoQry.SQL.Text :=
            'Create Table [' + TableName + '] (' +
//            '[ID]   counter,' +
            '[FieldName] string,'  +
            '[ViewX] integer,' +
            '[ViewY] integer,' +
            '[X1] integer,' +
            '[Y1] integer,' +
            '[X2] integer,' +
            '[Y2] integer)';
          try
            AdoQry.ExecSQL;
            Result := True;
          except
            on e: Exception do
              gLastError := '创建表' + '"Tab1"' + '失败!(' + e.Message + ')';
          end;
          AdoQry.SQL.Text :=
            'Create Unique Index iFieldName ON [' + TableName + ']([FieldName])';
          try
            AdoQry.ExecSQL;
            Result := True;
          except
            on e: Exception do
              gLastError := '创建表' + '"Tab1"' + '失败!(' + e.Message + ')';
          end;
        end;
      except
        on e: Exception do
          gLastError := '打开数据库' + MDBFile + '失败!(' + e.Message + ')';
      end;
    finally
      TblLst.Free;
      AdoQry.Free;
      ADOCon.Free
    end;
  end;

begin
  if not CreateAccessFile(MDBFile) then begin
    writelog(gLastError);
    Exit;
  end;

  CreateFieldTable('FieldInfo');
end;

function OpenTable(MDBFile, TableBame: string): TQuery;
var
  qry: TADOQuery;
begin
  qry := TADOQuery.Create(nil);
  qry.ConnectionString := format(MDBConnectionString, [MDBFile, '']);
  qry.SQL.Text := 'select * from [' + TableBame + ']';
  qry.Open;
  Result := TQuery(qry);
end;

 

你可能感兴趣的:(创建 Access 数据库 mdb 数据库(delphi))