Reputation: 1917
I can connect to an old Access
database with the following code:
bool LoadDb(const QString& file_path, QSqlDatabase& db_out, QSqlError& err)
{
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
static const auto DRIVER_NAME = R"({Microsoft Access Driver (*.mdb, *.accdb)})";
const auto connection_string = QString(R"(Driver=%1;DSN='';DBQ=%2)").arg(DRIVER_NAME, file_path);
db.setDatabaseName(connection_string);
if (!db.open())
{
err = db.lastError();
return false;
}
db_out = std::move(db);
return true;
}
But I would like to previously test that the driver ("Microsoft Access Database Engine") is installed so could I show a meaningful message for the user.
The following connection string does not work:
const auto connection_string = QString(R"(Driver=%1)").arg(DRIVER_NAME);
The error means nothing ... and it is in French:
[Microsoft][Pilote ODBC Microsoft Access]Erreur générale Impossible d'ouvrir la clé de Registre « Temporary (volatile) Ace DSN for process 0xa74 Thread 0xce4 DBC 0xb5518368 Jet ». QODBC3: Unable to connect
Any idea? Preferably portable code.
Upvotes: 0
Views: 595
Reputation: 1652
If you can access the SQLSTATE
you check for an SQLState of IM002
. I think IM002
is always returned if the driver cannot be found / loaded, while if for example the database file cannot be found because the path is wrong, you would get a HY000
SQLSTATE
:
For an invalid driver string I get:
SQLSTATE IM002; Native Error: 0; [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
For an invalid path I get:
SQLSTATE HY000; Native Error: -1044; [Microsoft][ODBC Microsoft Access Driver] Not a valid file name.
See here for more details about the values returned: https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlconnect-function
Upvotes: 1