Search code examples
c++sqloledboledbconnection

How do I add precautions to get around Microsoft.ACE.OLEDB.12.0 not registered?


When I use the following code on my home computer it works fine for me. However, I have to use it on multiple different machines.

"Provider = Microsoft.ACE.OLEDB.12.0;"

I was thinking that there could be a get around to this because I need it in a more universal format so that it works on multiple machines.

I have hoped that there could be a work around, maybe by including an alternative provider in the code (if that is possible) or an catch or if statement that will rerun the code but with an alternate provider if it cannot find the first one.

It would be changed to Microsoft.Jet.OLEDB.4.0

If anyone could scratch up a little bit of code to work around this so that my program could take into account both providers that would be great as it would make my projects more universal.

Background code (ignore unsafe SQL unless you want to fix it):

    OleDbDataReader^ openData(String^ fieldEntity, String^ field, String^ tableName)
    {
        String^ sqlstr = "SELECT * FROM ";
        sqlstr += tableName + " WHERE " + field + " = " + fieldEntity; 
        OleDbConnection^ conn = nullptr;
        conn = gcnew OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0;" +
            "Data Source =" + "myDatabaseV3.accdb");
        OleDbCommand^ cmd = nullptr;

        //fix this so that it will consider both providers.
        conn->Open();
        cmd = gcnew OleDbCommand(sqlstr, conn);
        OleDbDataReader^ reader = cmd->ExecuteReader(System::Data::CommandBehavior::CloseConnection); 
        return reader;
    }

Solution

  • I have solved this problem myself. I realised that I could you another try catch statement in my class to change the connection string if there is an exception

        conn = gcnew OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0;" +
            "Data Source =" + "myDatabaseV3.mdb");
        pause();
        OleDbCommand^ cmd = nullptr;
    
        //fix this so that it will come out of the current directiory 
        try {
            conn->Open();
        }
        catch (Exception^ ex)
        {
            conn->ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;" +
                "Data Source =" + "myDatabaseV3.accdb";
            conn->Open();
        }
    

    You could switch these around if you wanted the order of these doesn't really matter. Furthermore, if this solution is invalid you could have a nested try catch statement. However, my code in particular has this In a class and the way this is ran anyway is in a try catch in another part of the code so it is unnecessary for me.