开发者

Get the list of ODBC data source names programmatically using Delphi

开发者 https://www.devze.com 2023-04-11 09:23 出处:网络
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

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 standar开发者_如何学Cd components, so I can not use 3d party solutions.


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


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号