How to extract and store ODBC with driver pairs

73 Views Asked by At

I have an application that extracts all ODBC connections from the computer and puts them in a combo box. The user then chooses an ODBC connection out of the combo box and supplies the user name and password to then use to connect to the database. I have been able to connect to a simple Northwind Access database this way, but when testing against more sophisticated databases, I am receiving an error that the driver is wrong. This is what I'm using to get the ODBC connections:

RegistryKey sysODBC = (Registry.LocalMachine).OpenSubKey("SOFTWARE").OpenSubKey("ODBC").OpenSubKey("ODBC.INI").OpenSubKey("ODBC Data Sources");
string[] DSNArray = sysODBC.GetValueNames().ToArray();

OdbcConnection conn = new System.Data.Odbc.OdbcConnection(ConnectionString);

I see that there is a

conn.Driver

property, but am having a hard time finding out how to get the driver information to load and how what syntax would be needed to assign that to the driver property. Any help would be kindly appreciated.

1

There are 1 best solutions below

0
On BEST ANSWER

The code could be cleaned up a bit, but this worked for me:

public List<Tuple<string, string>> ListODBCsources()
{
    int envHandle = 0;
    const int SQL_FETCH_NEXT = 1;
    const int SQL_FETCH_FIRST_SYSTEM = 32;
    List<Tuple<string, string>> ODBCNameDriverList = new List<Tuple<string, string>>();            

    if (OdbcWrapper.SQLAllocEnv(ref envHandle) != -1)
    {
        int returnValue;
        StringBuilder serverName = new StringBuilder(1024);
        StringBuilder driverName = new StringBuilder(1024);
        int snLen = 0;
        int driverLen = 0;
        returnValue = OdbcWrapper.SQLDataSources(envHandle, SQL_FETCH_FIRST_SYSTEM, serverName, serverName.Capacity, ref snLen,
                driverName, driverName.Capacity, ref driverLen);
        while (returnValue == 0)
        {
            ODBCNameDriverList.Add(Tuple.Create(serverName.ToString(), driverName.ToString()));
            //MessageBox.Show(serverName + System.Environment.NewLine + driverName);
            returnValue = OdbcWrapper.SQLDataSources(envHandle, SQL_FETCH_NEXT, serverName, serverName.Capacity, ref snLen,
                driverName, driverName.Capacity, ref driverLen);
        }
    }
    return ODBCNameDriverList;
}