Get the list of ODBC data source names programmati

2020-03-02 03:17发布

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.

2条回答
孤傲高冷的网名
2楼-- · 2020-03-02 03:33

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

查看更多
聊天终结者
3楼-- · 2020-03-02 03:38

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.
查看更多
登录 后发表回答