
//////////////////////////////////////////////////
//  MS Access Data Access Components
//  Copyright © 2008-2014 Devart. All right reserved.
//////////////////////////////////////////////////

{$IFNDEF CLR}

{$I AccessDac.inc}
unit AccessCallUni;
{$ENDIF}

interface

uses
  Windows,
{$IFDEF CLR}
  System.Security, System.Text, System.Runtime.InteropServices,
{$ELSE}
  CLRClasses,
{$ENDIF}
  CRTypes;

const
  ODBCPP32 = 'odbccp32.dll';

type
  TSQLConfigDataSource =
    function(hwndParent: Integer;
    fRequest: Integer;
    lpszDriverString: string;
    lpszAttributes: string): Integer; {$IFNDEF CLR}stdcall;{$ENDIF}

{$IFDEF CLR}
  [SuppressUnmanagedCodeSecurity, DllImport(ODBCPP32, CharSet = CharSet.Auto, SetLastError = True, EntryPoint = 'SQLConfigDataSource')]
  function FnSQLConfigDataSource(hwndParent: Integer; fRequest: Integer; lpszDriverString: string; lpszAttributes: string): Integer; external;
{$ENDIF}

  procedure CreateNewDataBase(DBName: string);

implementation

uses
  SysUtils;

const
  ODBC_ADD_DSN = 1;


procedure CreateNewDataBase(DBName: string);
var
  hLib: HMODULE;
  SQLConfigDataSource: TSQLConfigDataSource;
begin
  if FileExists(DBName) then Exit;

  hLib := LoadLibraryEx(PChar(ODBCPP32), 0, LOAD_WITH_ALTERED_SEARCH_PATH);
  try
    if NativeUInt(hLib) = 0 then
      raise Exception.Create('Cannot load library: ' + ODBCPP32);
  {$IFDEF CLR}
    if GetProcAddress(hLib, PChar('SQLConfigDataSource')) <> nil then
      SQLConfigDataSource := FnSQLConfigDataSource
    else
  {$ELSE}
    SQLConfigDataSource := GetProcAddress(hLib, PChar('SQLConfigDataSource'));
    if @SQLConfigDataSource = nil then
  {$ENDIF}
      raise Exception.Create('SQLConfigDataSource function is not linked');

    if SQLConfigDataSource(0, ODBC_ADD_DSN, PChar('Microsoft Access Driver (*.mdb)'), PChar('CREATE_DB="' + DBName +'"')) <> 1 then
      raise Exception.Create('Cannot create ODBC alias');
  finally
    FreeLibrary(hLib);
  end;
end;

end.
