2

I am trying to connect to a Azure SQL Server database with Qt on Linux but I have not could make it. I tried some like this: Connection to SQL Server with qt but the connection is never opened.

My code is so simple:

QString connectionTemplate = "DRIVER={SQL SERVER};SERVER=%1;DATABASE=%2;";

QString connectionString = connectionTemplate.arg("tcp:my-database.database.windows.net,1433").arg("my-database");
for(int i = 0; i < QSqlDatabase::drivers().size(); i++) {
    qDebug() << QSqlDatabase::drivers().at(i);
}

QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");

db.setDatabaseName(connectionString);
db.setUserName("user@my-database");
db.setPassword("My password");
//db.setConnectOptions("Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;");
bool ok = false;
try {
    ok = db.open();
} catch(QException ex) {
    qDebug() << ex.what();
}

qDebug("%s=%d", "conexión abierta", ok);

 QSqlQueryModel *model = new QSqlQueryModel;

 QString query = "SELECT 1 AS test_col";
 model->setQuery(query, db);

 db.close();

I already have the QODB and QODBC3 drivers so I don't know why I am unable to make the connection.

Is some related to driver, Qt, Azure or similar?

2
  • did you find anything? Commented Apr 18, 2017 at 7:24
  • Nope, not yet :( Commented Apr 26, 2017 at 1:38

1 Answer 1

1

This is what I am doing and it works perfect for me:
Note: connName is the connection name on which I am opening the database.

QString connectionString = "Driver={ODBC Driver 13 for SQL Server};"
                           "Server=tcp:xxx.database.windows.net,1433;"
                           "Database=ABC;"
                           "Uid=aaa@xxx;"
                           "Pwd=***;"
                           "Encrypt=yes;"
                           "TrustServerCertificate=no;"
                           "Connection Timeout=30;";

QSqlDatabase db = QSqlDatabase::addDatabase("QODBC", connName);
db.setDatabaseName(connectionString);

if (db.open())
{
    return true;
}
else
{
    QString error = db.lastError().text();
    return false;
}
Sign up to request clarification or add additional context in comments.

3 Comments

how i can get connName for my Application
connName is the connection name that you provide when opening the database. Refer to the QSqlDatabase::addDatabase() function in Qt documentation.
i tried QSqlDatabase db = QSqlDatabase::addDatabase("QODBC3"); and its working fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.