问题
I have a freshly-installed MySQL server, which listens on localhost:3306. What is the correct way to connect to it from my Qt application?
回答1:
It turned out that I need to add MySQL to the ODBC data sources. I did that after following this video tutorial - https://youtu.be/K3GZidOwGmM.
After I had added the DSN, I successfully connected to the MySQL server using this code:
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
db.setDatabaseName("Driver={MySQL ODBC 5.3 Unicode Driver};DATABASE=test;");
db.setUserName("root");
db.setPassword("password");
if (!db.open()) {
qDebug() << db.lastError().text();
} else {
qDebug("success");
}
Note: You will need to replace MySQL ODBC 5.3 Unicode Driver
with the actual value listed in your DSN window. I got mine from here:

来源:https://stackoverflow.com/questions/25165525/how-to-connect-to-a-mysql-database-through-odbc-from-qt-application