Qt connection to MySQL is a simple matter, but it can be very simple.
QT gave us the hint only QMYSQL driver not loaded , let us have no clue. Accessing other databases can also be addressed in the same way.
QT Access MySQL requires 2 dynamic link library files, one is qt own MySQL 驱动插件 , the other is MySQL 提供的动态链接库 , indispensable. The database specified in the program to be accessed is MYSQL,QT automatically loaded MySQL 驱动插件 , and its implementation relies on MySQL 的动态链接库 access to MySQL.
#include <iostream>#include<QSqlDatabase>#include<QDebug>using namespacestd;intMain () {qsqldatabase D= Qsqldatabase::adddatabase ("Qmysql"); D.sethostname ("127.0.0.1"); D.setdatabasename ("DbName"); D.setport (3306); D.setusername ("Root"); D.setpassword ("Root"); if(D.open ()) cout<<"Hi mysql! Connection"<<Endl; Elsecout<<"failed"<<Endl; Qdebug ()<<qsqldatabase::d rivers () <<Endl; return 0;}
Running the above code, QT only gives us the prompt to drive without loading. The Qt 5 SDK defaults to the compiled MySQL driver plugin, which is located plugins/sqldrivers (under Mac OS libqsqlmysql.dylib , under Windows qsqlmysql.dll ), which can be used directly. But if we use Qt 4, unfortunately, we need to compile our own MySQL driver plug-ins, and different systems, different compilers in the steps differ, it takes a considerable amount of space to speak clearly. Next you need the MySQL dynamic link library:
1#include <QSqlDatabase>2#include <QSqlQuery>3#include <QSqlError>4#include <QPluginLoader>5#include <QDebug>6 7 voidloadmysqldriver ();8 9 intMainintargcChar*argv[]) {Ten One loadmysqldriver (); A return 0; - } - the voidLoadmysqldriver () { - Qpluginloader Loader; - //path to MySQL driver plugin -Loader.setfilename ("/users/stdu/qt5.6.1/5.6/clang_64/plugins/sqldrivers/libqsqlmysql.dylib"); +Qdebug () <<loader.load (); -Qdebug () <<loader.errorstring (); +}
Execute the above code, finally can see where the problem is, need to opt/..../ libmysqlclient.18.dylib this dynamic link library.
My MySQL is 5.7, which contains the dynamic link library islibmysqlclient.20.dylib,但我想了想这个库就是连接MYSQL的关键所在,将其改名为libmysqlclient.18.dylib,放在opt/.../下。连接成功。
Reference: http://qtdebug.com/DB-AccessMySQL.html
QT connection MySQL