參照網上教程,做的過程遇到很多問題,記下.
1.首先我將軟體中心搜到的mysql server和用戶端都裝上了.
2.sudo apt-get install libmysqlclient18 libmysqlclient-dev libmysqld-dev
3.參照qt creater的協助,搜sql可以找到database driver字樣
How to Build the QMYSQL Plugin on Unix and Mac OS X
You need the MySQL header files and as well as the shared librarylibmysqlclient.so. Depending on your Linux distribution you may need to install a package which is usually called "mysql-devel".
Tell qmake where to find the MySQL header files and shared libraries (here it is assumed that MySQL is installed in /usr/local) and runmake:
cd $QTDIR/src/plugins/sqldrivers/mysql qmake "INCLUDEPATH+=/usr/local/include" "LIBS+=-L/usr/local/lib -lmysqlclient_r" mysql.pro make
After installing Qt, as described in the Installing Qt for X11 Platformsdocument, you also need to install the plugin in the standard location:
cd $QTDIR/src/plugins/sqldrivers/mysql make install
於是 cd ~/work/Qt&Opencv_src/qt-everywhere-opensource-src-4.8.3/src/plugins/sqldrivers/mysql
qmake "INCLUDEPATH+=/usr/include/mysql" "LIBS+=-L/usr/lib/mysql/plugin -lmysqlclient_r" mysql.pro
出現錯誤:Failure to read QMAKESPEC conf file qt-everywhere-opensource-src-4.8.3/mkspecs/linux-g++/ qmake.conf
我就覺得很奇怪,因為我已經設定了環境變數,並且測試過可以編譯成功,這時發現 qmake讀取的不是mkspecs/linux-g++/ qmake.conf(qt庫安裝路徑的qmake.conf),而是源碼包的設定檔,於是在 ~/.profile添加一句
export QMAKESPEC=$QTDIR/mkspecs/linux-g++
這下可沒錯了.而接下去make的時候又出錯了
main.cpp:42:30: fatal error: qsqldriverplugin.h: No such file or directory
搜遍所有地方確實沒有那個標頭檔,於是意識到了,也許是因為我的mysql server是軟體中心安裝,而不是源碼包編譯安裝,很多東西包括標頭檔之類都沒裝上.因為make出錯,接下去就不能進行make install,也就不會產生所說的libqsqlmysql.so
咋辦呢,要麼remove mysql相關東西並重新編譯安裝.
搜著搜著,又有人說可以直接sudo apt-get install libqt4-sql-mysql 或者本來這東西就已經隨系統安裝了,然後將libqsqlmysql.so複製一份到$QTDIR/plugins/sqldrivers/ 下面,但在/usr/lib/qt4目錄下卻沒找到這個動態庫,直接find,發現居然存在於
/usr/lib/i386-linux-gnu/qt4/plugins/sqldrivers/libqsqlmysql.so 接下去的就不用我多說了吧.
做個demo測試一下,建立控制台程式,記得在pro檔案中 QT +=那裡加上sql,否則qmake是不會去找sql的相關部分的。先在mysql建立一個study資料庫。
C++ Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
|
#include <QtCore/QCoreApplication>
#include <QDebug>
#include <QSqlDatabase>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("study");
db.setUserName("root");
db.setPassword("666666");
if(!db.open())
{
qDebug() << "Unable to open database";
}
else
{
qDebug() << "Database connection established";
}
return a.exec();
} |
輸出
終於成功了,yeah~~~