Important: Please read the Qt Code of Conduct -

Database connection

  • Hello everyone,
    I'm begining in qt and i want to create connection between a simple qt application with database,but the connection always fails .I did many researchs but i didn't know
    where is the problem.
    Here is the mainWindow.cpp where i did the connection:

    #include <QMainWindow>
    #include <QtSql>
    #include <QtDebug>
    #include <QFileInfo>
    #include <QSqlDatabase>
    #include <QSqlError>
    #include <QSqlQuery>
    MainWindow::MainWindow(QWidget *parent) :
        ui(new Ui::MainWindow)
        QSqlDatabase mydb=QSqlDatabase::addDatabase("QODBC");
        mydb.setUserName("SYS ");
       // mydb.setPort(1521);
             ui->label->setText("no connexion");
            ui->label->setText("connected ");

    Dear friends ,I have two big points that I didn't understand :
    **1-**What is the difference between QOCI and QODBC and how to know which one i have to use ?
    **2-**I saw the qt Documentation where it says:0_1511020393018_qt docum.PNG
    but I didn't find in sqldrivers directory .So should I install the odbc header and include files?if yes I should ,how can Iinstall them?

    I'm student and I need this to work so I will be so glad if you help me to solve the problem
    And thanks in advance.

    [Moved to General and Desktop ~kshegunov]

  • Qt Champions 2019

    @mannel What is the database you're trying to connect to?
    Also do you really have a space in the user name?

    mydb.setUserName("SYS ");

  • Moderators

    please also note that ODBC interface sometimes also requires the credentials in the connection string (i don't know if it also works via the setter- and getter-methods)

    Example for a Microsoft SQL Server accessed via ODBC:

    QString connectionString = QString("Driver={SQL Server};Server=%1;Database=%2;Uid=%3;Pwd=%4").arg("").arg("MyDatabaseName").arg("Username").arg("Password");
    db = QSqlDatabase::addDatabase("QODBC");
    db.setDatabaseName( connectionString );

Log in to reply