1. Copy the libmysql.dll file in the mysql installation directory to the bin directory under the QT installation directory.
2. Create a new qt file and add it in the pro file
QT += sql
3. Main.cpp changed to the following: (test)
#include <QCoreApplication>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QtDebug>
void connect_mysql()
{
QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");
db.setHostName ("127.0.0.1"); // Connect to the database host name, you need to pay attention here (if you fill in "127.0.0.1", if you can not connect, change to localhost)
db.setPort (3306); // Connect to the database port number, consistent with the setting
db.setDatabaseName ("test"); // Connect the database name, consistent with the setting
db.setUserName ("root"); // Database user name, consistent with settings
db.setPassword ("1234"); // Database password, consistent with settings
db.open();
if(!db.open())
{
qDebug()<<"不能连接"<<"connect to mysql error"<<db.lastError().text();
return ;
}
else
{
qDebug()<<"连接成功"<<"connect to mysql OK";
}
QSqlQuery query(db);
query.exec("select * from tb1");
while(query.next()){
qDebug()<<query.value("username").toString();
}
}
int main(int argc,char *argv[])
{
QCoreApplication a(argc,argv);
connect_mysql();
return a.exec();
}
My mysql is 64-bit, but qt seems to be 32-bit (mingw version QT is 32-bit), does not match. So just use the above normal steps will not work
Step 1 is changed to:
First download mysql connector c 6.0.2 32-bit decompression package on the official website (I saved it to D: \ software_engineer \ MySQL5.6),
Then find the libmysql.dll file and copy it to the bin directory under the QT installation directory (D: \ software_engineer \ qt5.10.1 \ 5.10.1 \ msvc2013_64 \ bin)
Then follow steps 2, 3