Função em "C" para retornar a lista de Drivers ODBC, Windows

Aqui você poderá oferecer suas Contribuições, Dicas e Tutoriais (Texto ou Vídeo) que sejam de interesse de todos.

Moderador: Moderadores

Avatar do usuário
clodoaldomonteiro
Usuário Nível 4
Usuário Nível 4
Mensagens: 821
Registrado em: 30 Dez 2006 13:17
Localização: Teresina-PI
Contato:

Função em "C" para retornar a lista de Drivers ODBC, Windows

Mensagem por clodoaldomonteiro »

Boas a todos.
com a ajuda do Chat GPT, consegui uma função em C para retornas a lista de Drivers e assim poder verificar se o que ver precisa está na lista.
Compilado com xHarbour + BCC 7.30.

Código: Selecionar todos

//Linkar / informar a LIB obbc32.lib (Borland C) no seu arquivo .HBP
#pragma BEGINDUMP

   #include <stdio.h>
   #include <sql.h>
   #include <sqlext.h>

   #define MAX_DRIVER_COUNT 50

// Função para obter a lista de drivers ODBC
HB_FUNC( GETODBCDRIVERS )
{
    SQLHANDLE henv;
    SQLRETURN ret;
    static char drivers[MAX_DRIVER_COUNT][1024]; // Array para armazenar os nomes dos drivers
    static char result[1024 * MAX_DRIVER_COUNT];
    int count = 0;
    int i;
    
    SQLCHAR driver[1024]; // Declarado no início da função

    SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
    SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);

    ret = SQLDrivers(henv, SQL_FETCH_FIRST, driver, sizeof(driver), NULL, NULL, NULL, NULL);

    while (ret != SQL_NO_DATA && count < MAX_DRIVER_COUNT - 1) {
        snprintf(drivers[count], sizeof(drivers[count]), "%s", driver);
        count++;

        ret = SQLDrivers(henv, SQL_FETCH_NEXT, driver, sizeof(driver), NULL, NULL, NULL, NULL);
    }

    drivers[count][0] = '\0'; // Null-terminate the last string

    SQLFreeHandle(SQL_HANDLE_ENV, henv);

    // Concatenar os nomes dos drivers em uma única string
    result[0] = '\0';

    for (i = 0; i < count; i++) {
        strcat(result, drivers[i]);
        strcat(result, "\n");
    }
    
    hb_retc( result );
    
    return ;
}
#pragma ENDDUMP
Fico aberto a qualquer crítica ou sugestão.

Ps. Não sei porque o nome da função tem que ser em caixa alta.

Abraços.
At. Clodoaldo Monteiro
Linguagens: Clipper / Harbour
Área de Atuação: Sistemas de gestão para Prefeituras Municipais
Fones: (86)3223-0653, 98859-0236
www.simplesinformatica.com.br
alxsts
Colaborador
Colaborador
Mensagens: 3092
Registrado em: 12 Ago 2008 15:50
Localização: São Paulo-SP-Brasil

Função em "C" para retornar a lista de Drivers ODBC, Windows

Mensagem por alxsts »

Olá!

Bacana!
clodoaldomonteiro escreveu:Ps. Não sei porque o nome da função tem que ser em caixa alta.
A linguagem C é case-sensitive

Funciona? Tem exemplo de uso?
[]´s
Alexandre Santos (AlxSts)
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função em "C" para retornar a lista de Drivers ODBC, Windows

Mensagem por JoséQuintas »

Sei lá....
eu escreveu: how obtain driver odbc list from windows using harbour
chatgpt escreveu: To obtain a list of ODBC drivers installed on a Windows system using Harbour, you can use the Windows Registry to retrieve the information. The relevant information is stored in the Windows Registry under the registry key HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers.

Here's an example Harbour code snippet that retrieves the list of installed ODBC drivers:

harbour
Copy code
#include "registry.ch"

PROCEDURE ListODBCDrivers()
LOCAL hKey, nIndex, cDriverName, cValueName, cValueData

hKey := RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers", 0, KEY_READ)
IF hKey == 0
? "Error opening registry key:", GetRegistryError()
RETURN
ENDIF

nIndex := 0
cValueName := RegEnumValue(hKey, nIndex)

DO WHILE !Empty(cValueName)
? "ODBC Driver:", cValueName
nIndex++
cValueName := RegEnumValue(hKey, nIndex)
ENDDO

RegCloseKey(hKey)
RETURN
This code uses the registry.ch module to interact with the Windows Registry. Make sure that you have this module available in your Harbour environment. If it's not available, you can download it from the Harbour website or other reliable sources.

Save the above code in a file (e.g., ListODBCDrivers.prg) and then compile it using the Harbour compiler:

bash
Copy code
hbmk2 ListODBCDrivers.prg
Run the compiled program, and it should output the list of installed ODBC drivers on your Windows system.

Keep in mind that you may need administrative privileges to access certain registry keys. Additionally, the actual registry key structure may vary slightly depending on your Windows version and whether you are running a 32-bit or 64-bit system. Adjust the registry path accordingly if needed.
Convém atenção à última parte.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função em "C" para retornar a lista de Drivers ODBC, Windows

Mensagem por JoséQuintas »

Aqui nenhum dos dois compila.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função em "C" para retornar a lista de Drivers ODBC, Windows

Mensagem por JoséQuintas »

Outra opção do chatgpt que também não foi

Código: Selecionar todos

Option Explicit

Private Declare Function SQLDataSources Lib "odbc32.dll" Alias "SQLDataSourcesA" (ByVal henv As Long, ByVal fDirection As Integer, ByVal szDSN As String, ByVal cbDSNMax As Integer, ByRef pcbDSN As Integer, ByVal szDescription As String, ByVal cbDescriptionMax As Integer, ByRef pcbDescription As Integer) As Integer

Private Const SQL_FETCH_FIRST = 1
Private Const SQL_FETCH_NEXT = 2
Private Const SQL_FETCH_FIRST_USER = 31
Private Const SQL_FETCH_FIRST_SYSTEM = 32

Private Sub Form_Load()
    Dim henv As Long
    Dim dsn As String * 1024
    Dim desc As String * 1024
    Dim ret As Integer
    Dim lenDSN As Integer
    Dim lenDesc As Integer

    ' Allocate an environment handle
    ret = SQLAllocHandle(1, 0, henv)

    If ret <> 0 Then
        MsgBox "Error allocating environment handle."
        Exit Sub
    End If

    ' Retrieve the first user DSN
    ret = SQLDataSources(henv, SQL_FETCH_FIRST_USER, dsn, Len(dsn), lenDSN, desc, Len(desc), lenDesc)

    Do While ret = 0
        ' Print or process the DSN and Description
        Debug.Print "DSN: " & Left$(dsn, lenDSN) & ", Description: " & Left$(desc, lenDesc)

        ' Retrieve the next user DSN
        ret = SQLDataSources(henv, SQL_FETCH_NEXT, dsn, Len(dsn), lenDSN, desc, Len(desc), lenDesc)
    Loop

    ' Free the environment handle
    ret = SQLFreeHandle(1, henv)

    If ret <> 0 Then
        MsgBox "Error freeing environment handle."
    End If
End Sub
convertida pra isto

Código: Selecionar todos

#include "hbdyn.ch"
#define SQL_FETCH_FIRST        1
#define SQL_FETCH_NEXT         2
#define SQL_FETCH_FIRST_USER   31
#define SQL_FETCH_FIRST_SYSTEM 32

PROCEDURE Main

   LOCAL henv    := 0
   LOCAL dsn     := Space(1024)
   LOCAL desc    := Space(1024)
   LOCAL ret     := 0
   LOCAL lendsn  := 0
   LOCAL lendesc := 0

   ret := SQLDataSources( @henv, SQL_FETCH_FIRST_USER, @dsn, len(dsn), @lendsn, @desc, len(desc), @lendesc )
   DO WHILE ret = 0
      ? left( dsn, Lendsn )
      ret := SQLDataSources( henv, SQL_FETCH_NEXT, dsn, len(dsn),@ lendsn, desc, len(desc), @lendesc )
   ENDDO
   (ret)
   Inkey(0)

   RETURN

FUNCTION SQLDataSources( ... )


   RETURN ze_CallDllStd( "c:\windows\syswow64\odbc32.dll", "SQLDataSiourcesA", ... )


FUNCTION ze_CallDllStd( cDll, cName, ... )

   LOCAL hDll, xResult

   hDll    := hb_LibLoad( cDll )
   xResult := hb_DynCall( { cName, hDll, HB_DYN_CALLCONV_STDCALL }, ... )
   hb_LibFree( hDll )

   RETURN xResult
Como o fonte do chatgpt está visivelmente errado, o resultado também.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
clodoaldomonteiro
Usuário Nível 4
Usuário Nível 4
Mensagens: 821
Registrado em: 30 Dez 2006 13:17
Localização: Teresina-PI
Contato:

Função em "C" para retornar a lista de Drivers ODBC, Windows

Mensagem por clodoaldomonteiro »

alxsts escreveu:Olá!

Bacana!
clodoaldomonteiro escreveu:Ps. Não sei porque o nome da função tem que ser em caixa alta.
A linguagem C é case-sensitive

Funciona? Tem exemplo de uso?
Não é esse o caso, é que se eu criar a função em C, exemplo: "HB_FUNC( GetODBCDrivers )" , o compilador vai avisar que sentiu falta da função "GETODBCDRIVERS", ou seja, ele não enxerga que em HB_Func(), eu coloquei letra minúsculas.

Abraços.
At. Clodoaldo Monteiro
Linguagens: Clipper / Harbour
Área de Atuação: Sistemas de gestão para Prefeituras Municipais
Fones: (86)3223-0653, 98859-0236
www.simplesinformatica.com.br
Avatar do usuário
clodoaldomonteiro
Usuário Nível 4
Usuário Nível 4
Mensagens: 821
Registrado em: 30 Dez 2006 13:17
Localização: Teresina-PI
Contato:

Função em "C" para retornar a lista de Drivers ODBC, Windows

Mensagem por clodoaldomonteiro »

Quintas!
como falei acima, compilei com o xHarbour 123, e BCC 7.3, fui ajustando até dar certo.

O último ajuste foi incluir a Lib odbc32.lib, contida na pasta de lib da BCC.

E realmente o GPT dá muito fonte que não compila, e segundo ele, é por conta da versão de C que vc esteja usando.
Por exemplo, segundo ele, tem versão de C, que deixa vc declarar variáveis no meio da rotina, exemplo (variável "int i"):

Código: Selecionar todos

    for (int i; i = 0; i < count; i++) {
        strcat(result, drivers[i]);
        strcat(result, "\n");
    }
Mas para o meu compilador aceitou somente assim:

Código: Selecionar todos

HB_FUNC( GETODBCDRIVERS )
{
    SQLHANDLE henv;
    SQLRETURN ret;
    static char drivers[MAX_DRIVER_COUNT][1024]; // Array para armazenar os nomes dos drivers
    static char result[1024 * MAX_DRIVER_COUNT];
    int count = 0;
    int i;
..
...
...
    for (i = 0; i < count; i++) {
        strcat(result, drivers[i]);
        strcat(result, "\n");
    }
...
...
}
Exemplo de chamada da Função:

Código: Selecionar todos

Function Main()
Local mString
   mString := GETODBCDRIVERS()  //Retorna uma String com todos os Drivers ODBC instalados no Windows.
   ...
   ...
   Return nil
Mostra da relação de drivers instalados na minha máquina:

Código: Selecionar todos

SQL Server
Microsoft ODBC for Oracle
Microsoft Access Driver (*.mdb)
Microsoft Access-Treiber (*.mdb)
Driver do Microsoft Access (*.mdb)
Microsoft dBase Driver (*.dbf)
Microsoft dBase-Treiber (*.dbf)
Driver do Microsoft dBase (*.dbf)
Microsoft Excel Driver (*.xls)
Microsoft Excel-Treiber (*.xls)
Driver do Microsoft Excel(*.xls)
Microsoft Paradox Driver (*.db )
Microsoft Paradox-Treiber (*.db )
Driver do Microsoft Paradox (*.db )
Microsoft Text Driver (*.txt; *.csv)
Microsoft Text-Treiber (*.txt; *.csv)
Driver da Microsoft para arquivos texto (*.txt; *.csv)
Microsoft Visual FoxPro Driver
Microsoft FoxPro VFP Driver (*.dbf)
Microsoft dBase VFP Driver (*.dbf)
Microsoft Visual FoxPro-Treiber
Driver para o Microsoft Visual FoxPro
MySQL ODBC 5.3 ANSI Driver
MySQL ODBC 5.3 Unicode Driver
MariaDB ODBC 3.0 Driver
PostgreSQL ANSI
PostgreSQL Unicode
PostgreSQL ODBC Driver(ANSI)
PostgreSQL ODBC Driver(UNICODE)
Abraços
At. Clodoaldo Monteiro
Linguagens: Clipper / Harbour
Área de Atuação: Sistemas de gestão para Prefeituras Municipais
Fones: (86)3223-0653, 98859-0236
www.simplesinformatica.com.br
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função em "C" para retornar a lista de Drivers ODBC, Windows

Mensagem por JoséQuintas »

Achei um com declarações mais completas.

Código: Selecionar todos

Const SQL_NULL_HANDLE = 0
Const SQL_HANDLE_ENV = 1
Const SQL_FETCH_NEXT = 1
Const SQL_FETCH_FIRST = 2
Const SQL_SUCCESS = 0
Const SQL_ATTR_ODBC_VERSION = 200
Const SQL_OV_ODBC2 = 2
Const SQL_IS_INTEGER = -6

Dim nRetCode As Long

Private Declare Function SQLDrivers Lib "odbc32.dll" (ByVal _
    EnvironmentHandle As Long, ByVal Direction As Integer, _
    ByVal DriverDescription As String, ByVal BufferLength1 As Integer, _
    DescriptionLengthPtr As Integer, ByVal DriverAttributes As String, _
    ByVal BufferLength2 As Integer, AttributesLengthPtr As Integer) As Integer

' Note that pointers to numbers are passed as numbers by reference!
Private Declare Function SQLDataSources Lib "odbc32.dll" (ByVal _
    EnvironmentHandle As Long, ByVal Direction As Integer, _
    ByVal ServerName As String, ByVal BufferLength1 As Integer, _
    NameLength1Ptr As Integer, ByVal Description As String, _
    ByVal BufferLength2 As Integer, NameLength2Ptr As Integer) As Integer


Private Declare Function SQLFreeHandle Lib "odbc32.dll" (ByVal _
    HandleType As Integer, ByVal Handle As Long) As Integer

Private Declare Function SQLAllocHandle Lib "odbc32.dll" (ByVal _
    HandleType As Integer, ByVal InputHandle As Long, _
    OutputHandlePtr As Long) As Integer

Private Declare Function SQLSetEnvAttr Lib "odbc32.dll" (ByVal _
    EnvironmentHandle As Long, ByVal EnvAttribute As Long, _
    ByVal ValuePtr As Long, ByVal StringLength As Long) As Integer


Private Declare Function SQLDisconnect Lib "odbc32.dll" (ByVal _
    ConnectionHandle As Long) As Integer

'//This function will print list of installed driver name and attributes
Private Sub ListODBCDrivers()

  ' Prints a list of ODBC drivers on system

  Dim lHEnv       As Long
  Dim sDriverDesc    As String * 1024
  Dim sDriverAttr    As String * 1024
  Dim sDriverAttributes As String
  Dim nDriverDescLength As Integer
  Dim nAttrLength As Integer
  Dim x As Integer
  Dim sAll As String

  ' Allocate an environment handle.
  nRetCode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, lHEnv)

  ' Set ODBC behavior
  nRetCode = SQLSetEnvAttr(lHEnv, SQL_ATTR_ODBC_VERSION, _
      SQL_OV_ODBC2, SQL_IS_INTEGER)

  ' Get first driver
  nRetCode = SQLDrivers(lHEnv, _
      SQL_FETCH_FIRST, _
      sDriverDesc, _
      Len(sDriverDesc), _
      nDriverDescLength, _
      sDriverAttr, _
      Len(sDriverAttr), _
      nAttrLength)

  sAll = ""

  Me.WindowState = vbMaximized
  Me.AutoRedraw = True

  Do While nRetCode = SQL_SUCCESS

    '//Replace NULL separators with colons in attribute string
    sDriverAttributes = Left$(sDriverAttr, nAttrLength - 1)
    sDriverAttributes = Replace(sDriverAttributes, Chr(0), " : ")

    '//Remove NULL in ODBC Driver name
    sDriverDesc = Left$(sDriverDesc, nDriverDescLength)
    sDriverDesc = Replace(sDriverDesc, Chr(0), "")

    sAll = sAll & sDriverDesc & " ==> " & sDriverAttributes & vbCrLf

    Me.Print sDriverDesc                '//Print driver name
    Me.Print sDriverAttributes             '//Print driver attribute
    Me.Print String(100, "-")

    Debug.Print sDriverDesc              '//Print driver name
    Debug.Print sDriverAttributes           '//Print driver attribute
    Debug.Print String(100, "-")

    '//Next data source
    nRetCode = SQLDrivers(lHEnv, _
        SQL_FETCH_NEXT, _
        sDriverDesc, _
        Len(sDriverDesc), _
        nDriverDescLength, _
        sDriverAttr, _
        Len(sDriverAttr), _
        nAttrLength)
  Loop

  'Debug.Print "ODBC Drivers"
  'Debug.Print sAll

  nRetCode = SQLFreeHandle(SQL_HANDLE_ENV, lHEnv)
End Sub

Private Sub Form_Load()
  ListODBCDrivers
End Sub
https://binaryworld.net/Main/CodeDetail ... =3875#copy

Basicamente é a mesma coisa, mas aqui mostra os tipos necessários, e daria pra fazer sem linguagem C, e sem a LIB, diretamente com a DLL do Windows.

Uma coisa a prestar atenção é na declaração, não apenas no tipo.

No harbour usamos funcao( x, @y ) pra passar por referência, isso é feito na chamada da função.
No VB isso não é na chamada, é na função. É a função que vai dizer se é por referência. function funcao( byval x, y ), o x é normal e o y é por referência
Além disso, como são linguagens de programação diferentes, a variável por referência precisa ter conteúdo adequado.
Se vai retornar uma string de até 1024 caracteres, precisa passar a variável string com no mínimo 1024 caracteres, ou dá GPF.
Isso é porque por referência é o "pointer", a posição da memória aonde a variável está, se definir tamanho pequeno, o resultado vai invadir memória que não pertence à variável/programa, por isso windows acusa GPF ou violação de memória.
É por isso que geralmente criam funções intermediárias no harbour, pra tratar esse tipo de coisa e o programador não se preocupar com isso.

E com base nisso dá pra aproveitar muito fonte pronto do VB6, não apenas esse.

Quem usa a LIB do ACBR faz muito uso disso, talvez sem ter percebido, porque pega o fonte pronto que eles fornecem.

Tava aqui pensando... se alimentar a IA com isso, ela pode fornecer muita coisa pronta pro harbour !!!
Também pensando.... a IA ainda não sabe pesquisar direito, acaba sempre dependendo de mais informação, ainda tem muito a aprender. Só não sei dizer se está humana demais ou de menos.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
Itamar M. Lins Jr.
Administrador
Administrador
Mensagens: 7928
Registrado em: 30 Mai 2007 11:31
Localização: Ilheus Bahia
Curtiu: 1 vez

Função em "C" para retornar a lista de Drivers ODBC, Windows

Mensagem por Itamar M. Lins Jr. »

Olá!

Código: Selecionar todos

C:\fontes>powershell  Get-OdbcDriver > drivers-odbc.txt

Name      : Driver da Microsoft para arquivos texto (*.txt; *.csv)
Platform  : 32-bit
Attribute : {APILevel, DriverODBCVer, FileUsage, Driver...}

Name      : Driver do Microsoft Access (*.mdb)
Platform  : 32-bit
Attribute : {APILevel, DriverODBCVer, FileUsage, Driver...}

Name      : Driver do Microsoft dBase (*.dbf)
Platform  : 32-bit
Attribute : {APILevel, DriverODBCVer, FileUsage, Driver...}

Name      : Driver do Microsoft Excel(*.xls)
Platform  : 32-bit
Attribute : {APILevel, DriverODBCVer, FileUsage, Driver...}

Name      : Driver do Microsoft Paradox (*.db )
Platform  : 32-bit
Attribute : {APILevel, DriverODBCVer, FileUsage, Driver...}

Name      : Microsoft Access Driver (*.mdb)
Platform  : 32-bit
Attribute : {APILevel, DriverODBCVer, FileUsage, Driver...}

Name      : Microsoft Access-Treiber (*.mdb)
Platform  : 32-bit
Attribute : {APILevel, DriverODBCVer, FileUsage, Driver...}

Name      : Microsoft dBase Driver (*.dbf)
Platform  : 32-bit
Attribute : {APILevel, DriverODBCVer, FileUsage, Driver...}

Name      : Microsoft dBase-Treiber (*.dbf)
Platform  : 32-bit
Attribute : {APILevel, DriverODBCVer, FileUsage, Driver...}

Name      : Microsoft Excel Driver (*.xls)
Platform  : 32-bit
Attribute : {APILevel, DriverODBCVer, FileUsage, Driver...}

Name      : Microsoft Excel-Treiber (*.xls)
Platform  : 32-bit
Attribute : {APILevel, DriverODBCVer, FileUsage, Driver...}

Name      : Microsoft ODBC for Oracle
Platform  : 32-bit
Attribute : {APILevel, FileUsage, Driver, ConnectFunctions...}

Name      : Microsoft Paradox Driver (*.db )
Platform  : 32-bit
Attribute : {APILevel, DriverODBCVer, FileUsage, Driver...}

Name      : Microsoft Paradox-Treiber (*.db )
Platform  : 32-bit
Attribute : {APILevel, DriverODBCVer, FileUsage, Driver...}

Name      : Microsoft Text Driver (*.txt; *.csv)
Platform  : 32-bit
Attribute : {APILevel, DriverODBCVer, FileUsage, Driver...}

Name      : Microsoft Text-Treiber (*.txt; *.csv)
Platform  : 32-bit
Attribute : {APILevel, DriverODBCVer, FileUsage, Driver...}

Name      : SQL Server
Platform  : 32-bit
Attribute : {APILevel, FileUsage, Driver, ConnectFunctions...}

Name      : SQL Server
Platform  : 64-bit
Attribute : {APILevel, FileUsage, Driver, ConnectFunctions...}

Name      : PostgreSQL ODBC Driver(ANSI)
Platform  : 64-bit
Attribute : {APILevel, FileUsage, Driver, ConnectFunctions...}

Name      : PostgreSQL ODBC Driver(UNICODE)
Platform  : 64-bit
Attribute : {APILevel, FileUsage, Driver, ConnectFunctions...}
Saudações,
Itamar M. LIns Jr.
Saudações,
Itamar M. Lins Jr.
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função em "C" para retornar a lista de Drivers ODBC, Windows

Mensagem por JoséQuintas »

Converti o de VB6 pra harbour, mas a lista é incompleta.

Código: Selecionar todos

PROCEDURE Main

   LOCAL aItem

   setmode( 33,100)
   CLS
   FOR EACH aItem IN ListODBCDrivers()
      ? aItem
   NEXT
   Inkey(0)
   RETURN

#define SQL_NULL_HANDLE       0
#define SQL_HANDLE_ENV        1
#define SQL_FETCH_NEXT        1
#define SQL_FETCH_FIRST       2
#define SQL_SUCCESS           0
#define SQL_ATTR_ODBC_VERSION 200
#define SQL_OV_ODBC2          2
#define SQL_IS_INTEGER       -6

//This function will print list of installed driver name and attributes
FUNCTION ListODBCDrivers()

  // Prints a list of ODBC drivers on system

  LOCAL nRetCode
  LOCAL lHEnv             := 0
  LOCAL sDriverDesc       := Space(1024)
  LOCAL sDriverAttr       := Space(1024)
  LOCAL sDriverAttributes
  LOCAL nDriverDescLength := 0
  LOCAL nAttrLength       := 0
  LOCAL aList             := {}
  MEMVAR hDll
  PRIVATE hDll

   //hDll := hb_libLoad( "c:\windows\syswow64\odbc32.dll" )
   hDll := hb_libLoad( "c:\windows\system32\odbc32.dll" )
  // Allocate an environment handle.
  /* nRetCode := */ SQLAllocHandle( SQL_HANDLE_ENV, SQL_NULL_HANDLE, @lHEnv )

  // Set ODBC behavior
  /* nRetCode := */ SQLSetEnvAttr( lHEnv, SQL_ATTR_ODBC_VERSION, ;
      SQL_OV_ODBC2, SQL_IS_INTEGER )

  // Get first driver
  nRetCode := SQLDrivers( lHEnv, ;
      SQL_FETCH_FIRST, ;
      @sDriverDesc, ;
      Len( sDriverDesc ), ;
      @nDriverDescLength, ;
      @sDriverAttr, ;
      Len( sDriverAttr ), ;
      @nAttrLength )

  Do While nRetCode = SQL_SUCCESS

    //Replace NULL separators with colons in attribute string
    sDriverAttributes = Left( sDriverAttr, nAttrLength - 1 )
    sDriverAttributes = StrTran( sDriverAttributes, Chr(0), " : " )

    //Remove NULL in ODBC Driver name
    sDriverDesc = Left( sDriverDesc, nDriverDescLength )
    sDriverDesc = StrTran( sDriverDesc, Chr(0), "" )

    AAdd( aList, sDriverDesc )
   ( sDriverAttributes )

    //Next data source
    nRetCode := SQLDrivers( lHEnv, ;
        SQL_FETCH_NEXT, ;
        @sDriverDesc, ;
        Len( sDriverDesc ), ;
        @nDriverDescLength, ;
        @sDriverAttr, ;
        Len( sDriverAttr ), ;
        @nAttrLength )
  ENDDO

  /* nRetCode := */ SQLFreeHandle( SQL_HANDLE_ENV, lHEnv )

  hb_libFree( hDll )

   RETURN aList

FUNCTION SQLDrivers( ... );     RETURN CallThis( "SQLDrivers", ... )
FUNCTION SQLDataSources( ... ); RETURN CallThis( "SQLDataSources", ... )
FUNCTION SQLFreeHandle( ...);   RETURN CallThis( "SQLFreeHandle", ... )
FUNCTION SQLAllocHandle( ... ); RETURN CallThis( "SQLAllocHandle", ... )
FUNCTION SQLSetEnvAttr( ... );  RETURN CallThis( "SQLSetEnvAttr", ... )
FUNCTION SQLDisconnect( ... );  RETURN CallThis( "SQLDisconnect", ... )

#include "hbdyn.ch"

FUNCTION CallThis( cFunction, ... )

   MEMVAR hDll

   RETURN hb_DynCall( { cFunction, hDll, HB_DYN_CALLCONV_STDCALL }, ... )
driver.png
driver.png (11.68 KiB) Exibido 9653 vezes
Achei estranho, mas tanto faz usar odbc32.dll da pasta system32 ou syswow64

Achei estranho a definição de FIRST e NEXT estarem diferentes entre o fonte C e o VB, mas se inverter não funciona.

Comparei o fonte C com esse, até tem algumas diferenças de definição, mas não faz diferença alterar.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função em "C" para retornar a lista de Drivers ODBC, Windows

Mensagem por JoséQuintas »

Aí vém uma pergunta super interessante:

Será que o BORLAND C se comunica melhor com 32 bits?

Quem puder testar o fonte com seu compilador pode ajudar a tirar a dúvida.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
ivanil
Usuário Nível 3
Usuário Nível 3
Mensagens: 166
Registrado em: 11 Set 2004 15:13
Localização: Florianópolis/SC

Função em "C" para retornar a lista de Drivers ODBC, Windows

Mensagem por ivanil »

Não há diferença...
Anexos
2024-01-05_192550.png
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função em "C" para retornar a lista de Drivers ODBC, Windows

Mensagem por JoséQuintas »

Esse teste foi com o fonte em C, que inclusive aqui não compilou com mingw.
Mas me referi ao fonte em PRG.
Não entendi porque a lista dele é menor.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Responder