8

I saw several examples where the list of the source names were took from registry (HKEY_LOCAL_MACHINE\Software\ODBC\ODBC.INI\ODBC Data Sources). Is there any other way to get the list of ODBC data sources names?

I need to work only with Delphi standard components, so I can not use 3d party solutions.

Cœur
  • 37,241
  • 25
  • 195
  • 267
RBA
  • 12,337
  • 16
  • 79
  • 126
  • What is the problem with read that registry location? – RRUZ Oct 06 '11 at 15:55
  • 1
    There isn't a problem with that. It's even simpler than accessing ODBC32.DLL. I'm asking how can I accomplish this in the right way. – RBA Oct 06 '11 at 20:39

2 Answers2

6

You have to use SQLDataSources function from ODBC32.DLL. For example.

da-soft
  • 7,670
  • 28
  • 36
1

As @da-soft stated in their answer, SQLDataSources in ODBC32.DLL will do this. However, as the link they provided is no longer working, here's an actual example (adapted from Menno Avegaar's answer to an old delphi groups post):

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

function SQLAllocEnv(var EnvironmentHandle: Pointer): SmallInt; stdcall; external 'odbc32.dll';
function SQLFreeEnv(EnvironmentHandle: Pointer): SmallInt; stdcall; external 'odbc32.dll';
function SQLDataSources(
  EnvironmentHandle: Pointer;
  Direction: Word;
  ServerName: PAnsiChar;
  BufferLength1: SmallInt;
  var NameLength1: SmallInt;
  Description: PAnsiChar;
  BufferLength2: SmallInt;
  var NameLength2: SmallInt): SmallInt; stdcall; external 'odbc32.dll';

const
  SQL_SUCCESS = 0;
  SQL_NO_DATA = 100;
  SQL_FETCH_NEXT = 1;
  SQL_FETCH_FIRST = 2;
  SQL_MAX_DSN_LENGTH = 32;
  SQL_MAX_OPTION_STRING_LENGTH = 256;

var
  EnvironmentHandle: Pointer;
  Buffer1: array[0..SQL_MAX_DSN_LENGTH] of AnsiChar;
  Buffer2: array[0..SQL_MAX_OPTION_STRING_LENGTH] of AnsiChar;
  Len1, Len2: SmallInt;
  ServerName, Description: String;
begin
  if SQLAllocEnv(EnvironmentHandle) = SQL_SUCCESS then
  begin
    try
      if SQLDataSources(
        EnvironmentHandle,
        SQL_FETCH_FIRST,
        Buffer1,
        SizeOf(Buffer1),
        Len1,
        Buffer2,
        SizeOf(Buffer2),
        Len2) = SQL_SUCCESS then
      repeat
        SetString(ServerName, Buffer1, Len1);   
        SetString(Description, Buffer2, Len2);
        Writeln('Name:'+ServerName);
        Writeln('Description:'+Description);
        Writeln('');
      until SQLDataSources(
        EnvironmentHandle,
        SQL_FETCH_NEXT,
        Buffer1,
        SizeOf(Buffer1),
        Len1,
        Buffer2,
        SizeOf(Buffer2),
        Len2) = SQL_NO_DATA;
    finally
      SQLFreeEnv(EnvironmentHandle);
    end;
  end;
  Readln;
end.
Adam Henderson
  • 309
  • 3
  • 12