This article describes the use of QT 4.8.2 to connect to the MySQL (Ver 14.14 distrib 5.5.43) database under Ubuntu12.04 (+ bit).
1. Install Qt and MySQL
If the above software is not installed, refer to my blog installation.
- Install qt:ubuntu12.04 under Installation Qt4 summary-http://www.cnblogs.com/gaohongchen01/p/4204860.html
- Install mysql:ubuntu12.04 under installation Apache+php+mysql-http://www.cnblogs.com/gaohongchen01/p/3710992.html
2. Installing the QT MySQL driver
Download the installation package Libqt4-sql-mysql_4.8.1-0ubuntu4.8_amd64.deb
sudo apt-get download libqt4-sql-mysql
Unpacking the installation package
ar -x libqt4-sql-mysql_4. 8.1-0ubuntu4.8_amd64.deb
Decompression Data.tar.lzma file appears Data.tar file
LZMA-DK data. tar. Lzma
Unzip the Data.tar file
tar -xvf data. Tar
Copy the extracted libqsqlmysql.so files to the Sqldrivers folder under the Qtsdk Lib search directory.
The qtsqk Lib search directory can be obtained through the following QT programs:
Qdebug () << qcoreapplication::librarypaths ();
3. Programming QT Program Connection MySQL
For applications that use the SQL class, add the following command line to their. Pro file:
QT + = SQL
Write a console application, The program in MAIN.C is:
#include <QCoreApplication>#include<QtSql/QSqlDatabase>#include<QtSql/QSqlError>#include<QtSql/QSqlQuery>#include<QTextCodec>#include<QtDebug>#include<QStringList>#include<iostream>intMainintargcChar*argv[]) {Qcoreapplication A (argc, argv); Qtextcodec::setcodecforcstrings (Qtextcodec::codecforlocale ()); //Qtextcodec::setcodecfortr (Qtextcodec::codecforlocale ()); //Qtextcodec::setcodecforlocale (Qtextcodec::codecforlocale ()); //Qcoreapplication::addlibrarypath ("/usr/lib/i386-linux-gnu/qt4/plugins/");Qdebug () <<qcoreapplication::librarypaths (); Qdebug ()<<Qsqldatabase::d rivers (); Qsqldatabase DB=qsqldatabase::adddatabase ("Qmysql"); Db.sethostname ("localhost"); Db.setdatabasename ("ghcdb"); Db.setusername ("Root"); Db.setpassword ("123456"); if(!Db.open ()) {Qdebug ()<<db.lasterror (). Text () <<Endl; return false; } returna.exec ();}
Reference: http://www.cnblogs.com/qianyuming/archive/2011/08/13/2137402.html
Ubuntu12.04 qt connected MySQL database