Click here to Skip to main content
15,886,771 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I an learning QT creator. I found a sample program to connect to MYSQL. When I run it, I get these errors

QSqlDatabase: QMYSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QMYSQL QMYSQL3 QPSQL QPSQL7

I have googled this for hours. Many suggest compiling the MYSQL plugin from scratch. I found the instructions didn't work. The path names were incorrect.

I am using Ubuntu 14.04 LTS. MYSQL version is 5.5.46-0ubuntu0.14.04.2.

QT creator version is 5.5.1. QT version 5.5.5

Here is the same qt project file
----------------------------------------------------------
QT       += core
QT       -= gui
QT       += webkit webkitwidgets
QT       += sql
TARGET = TestMySqlExample
CONFIG   += console
CONFIG   -= app_bundle


TEMPLATE = app

SOURCES += main.cpp

Here is the sample code
--------------------------------------------------------------------
C++
#include <QCoreApplication>
#include <QApplication>
#include <QtSql/QSql>
#include <QtSql/QSqlDatabase>
#include <lQtSql/QSqlDriver>
#include <QtSql/QSqlQuery>
#include <QDebug>

bool createConnection();

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    

    if (!createConnection()){

        qDebug() << "Not connected!";
        return 1;
    }
    else{

        qDebug() << "Connected!";

        QSqlQuery query;
        query.exec("SELECT Name FROM student");

        while (query.next()) {
            QString name = query.value(0).toString();
            qDebug() <<"name:" << name;
        }

        return 0;
    }

    return app.exec();
}
bool createConnection(){
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setDatabaseName("mydb");
    db.setUserName("root");
    db.setPassword("moonpie");
    if (!db.open()) {
        qDebug() << "Database error occurred";
        return false;
    }
    return true;
}
Posted
Updated 26-Nov-15 22:09pm
v2

1 solution

See http://doc.qt.io/qt-5/qsqldatabase.html#QSqlDatabase-2[^] for correct instantiation of the QSqlDatabase class.
 
Share this answer
 
Comments
JohnnyG62 29-Nov-15 17:36pm    
I looked at your link and tried the code example and got many compile errors. I had to remove QT then I reinstalled it using these instructions
http://zetcode.com/gui/qt5/introduction/
then the code I posted above worked.
I guess installing QT from apt-get doesn't install a unusable mysql environment.
Richard MacCutchan 30-Nov-15 4:14am    
It's no good making guesses, and randomly copying code from the internet. You need to understand why errors occur.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900