QT-Connnect to Mysql Database Tutorial


Qt Version:  4.7.4
Date Added: 2012-06-23 16:00:43
Introduction :
This tutorial is about connecting to MYSQL database and showing its contents in QT QTableWidget.
What is done here is connecting to MYSQL database with QSqlDatabase database class, querying database with QSqlQuery class and showing contents in QTableWidget.
After initializing QTableWidget instance, row and column numbers must be set properly to avoid confusing result. Otherwise, field values on each row may be incorrect.
Now, let's see detailed information and the entire C++ code:
#include <QtGui>
#include <QtSql>
int main(int argc,char* argv[])
{
    QApplication app(argc,argv);
    QTableWidget* table = new QTableWidget();
    table->setWindowTitle("Connect to Mysql Database Example");   
    
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("192.168.11.3");
    db.setDatabaseName("menudb");
    db.setUserName("root");
    db.setPassword("test");
    if (!db.open()) 
    {
      QMessageBox::critical(0, QObject::tr("Database Error"),
			    db.lastError().text());    
    }
    
    QSqlQuery query("SELECT * FROM test");   
    
    table->setColumnCount(query.record().count());
    table->setRowCount(query.size());
    
    int index=0;
    while (query.next()) 
    {      
	table->setItem(index,0,new QTableWidgetItem(query.value(0).toString()));
	table->setItem(index,1,new QTableWidgetItem(query.value(1).toString()));	
	index++;
    }
    
    table->show();
    return app.exec();
}

Output :

QT Connect to MYSQL Tutorial


Browse Some Other Qt Examples
QLcdNumberQTimer
QPushButtonQMessageBox
QTabWidgetQtConcurrent
QLabelQList
QKeyEventQSlider
QFontDialogQSpinBox
QTableWidgetQTextBrowser
Qt StylesheetsQCheckBox
QComboBoxQCloseEvent
QProgressBarQProgressDialog
QTreeWidgetQSignalMapper

Want any example ? Feel free to tell us:
(Max. 2000 characters)
Please note that we do not guarantee to respond.Thanks.

C++
OpenSceneGraph
Fundamentals
QT
Boost
wxWidgets
Java
Python



Copyright 2011 - 2013 | All Rights Reserved
All trademarks are properties of their respective owners.
Contact| Privacy Policy| About Us