Difference between revisions of "Qt4/Qt-Creator Read MySql Table (Console Mode)"

From dftwiki3
Jump to: navigation, search
(Created page with "--~~~~ ---- {| | width="40%" | __TOC__ | <bluebox> right | 80px <br /> <br /> This tutorial illustrates how to use Qt Creator to write a simply program...")
 
(QtCreator)
Line 83: Line 83:
 
</source>
 
</source>
  
=QtCreator=
+
=QtCreator Screen-Shot=
  
<center>[[Image:QtCreatorMySqlProgram.png]]</center>
+
<center>[[Image:QtCreatorMySqlProgram.png|800px]]</center>
  
  

Revision as of 15:12, 24 February 2011

--D. Thiebaut 15:11, 24 February 2011 (EST)


QtCreator.png



This tutorial illustrates how to use Qt Creator to write a simply program that accesses a MySql database and reads the contents of a table.



Setup

We assume that you have installed Qt Creator and Qt 4 on your Mac (or Windows/Linux platform).

Steps

  • Follow the steps of the Hello World example, and create a project called mySqlSimpleTable.
  • Enter the code below in main.cpp:
// mySqlSimpleTable project
// main.cpp
// D. Thiebaut
// This program accesses a MySql database server, opens up a
// connection to a database (called dummy), with user name
// "dummy" and password "xxxxxx", and reads the full contents
// of a table called "table1".
// The contents of the table is dumped on the console.
//

#include <QtCore/QCoreApplication>
#include <QtSql>
#include <qtextstream.h>
#include <iostream>

using namespace std;

int main(int argc, char *argv[]) {
    //--- use a QTextStream: it makes it easier to output ---
    //--- QString to cout.                                ---
    QTextStream cout(stdout, QIODevice::WriteOnly);
    
    //--- define the database connection ---
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("xgridmac.dyndns.org");  // host
    db.setDatabaseName("dummy");            // database
    db.setUserName("dummy");                // user
    db.setPassword("xxxxxx");               // password
    
    //--- attempt to open it ---
    bool ok = db.open();

    if ( ok ) {
        //--- we're good! ---
        cout << "Database open\n";
        
        //--- run a query and print data returned ---
        QSqlQuery query( "select * from table1" );
        while (query.next()) {
            int Id = query.value(0).toInt();
            QString word = query.value(1).toString();
            cout <<  word << endl;
            }
        
        //--- close connection to database
        db.close();
    }
    else
        //--- something went wrong ---
        cout << "Error opening database\n";

    return 0; 
}

QtCreator Screen-Shot

QtCreatorMySqlProgram.png