[SOLVED] Connect to SQL using Qt

  • Hey,

    I've been searching around a fair amount for a solution and been trying for the last week to get my connection to SQL working but I seems to be banging my head against the wall, which probably means my mistake is a simple set up one that I'm overlooking.

    So any help anyone can give me would be much appreciated.

    SS from SQL manager - http://imgur.com/c3NZq2H
    Server LancesPC\SQLEXPRESS

    SS from ODBC Connections in control panel
    http://imgur.com/cdH4JlR (apparently I had to set up the driver as SQL Server.

    My Qt code.

    @#include <QCoreApplication>
    #include <QtSql>
    #include <QtDebug>

    int main(int argc, char *argv[])
    QCoreApplication a(argc, argv);

    QString servername = "LANCESPC\\SQLEXPRESS";
    QString dbname = "TEST1";
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
    QString dsn = QString("DRIVER=(SQL Server);SERVER=%1;DATABASE=%2;Trusted_Connection=Yes;").arg(servername).arg(dbname);
        qDebug() << "Opened!";
        qDebug() << "Error = " << db.lastError().text();
    return a.exec(&#41;;


    And most importantly, the error message

    Any help in pointing out where I have gone wrong would be really appreciated.



  • Moderators

    I'm not a db expert, so I don't know if that matters, but shouldn't it be
    QString dsn = QString("DRIVER={SQL Server};SERVER=%1;DATABASE=%2;Trusted_Connection=Yes;")
    .arg(servername, dbname);@
    i.e. {} instead of () ?

  • Hi, actually you can get by even easier:
    QString dsn = QString("Driver=SQL Server; Server=%1; Database=%2;Trusted_Connection=Yes;").arg(servername, dbname);

    Haven't tried SQL Express recently, I use vanilla SQL Server, but Qt should work the same. (If you want to look at my DSN fiddling etc. my opensource healthcare .cpp file is here "CWDB.cpp":https://github.com/Clinware/CWDB/blob/master/CWDB.cpp )

    EDIT: forgot about your error message: "data source name not found"
    I get the same error often when I try using a name for the server, better is to use the ip number, like "" if SQL Express is running on the same PC as your Qt. Also make sure it's listening on port 1433, if not you'll have to call "setPort":http://qt-project.org/doc/qt-5/qsqldatabase.html#setPort

  • Thanks for the help Chris that seemed to work :)

    @Hskoglund - I'll give it a go. Hopefully that should make the code a bit better.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.