IMAN4K
IMAN4K

Reputation: 1345

Remote connectivity issue with QSqlDatabase [ODBC]

I'm trying to make a connection to a remote SQL server :

QSqlDatabase db = QSqlDatabase::addDatabase("QODBC3");
    db.setDatabaseName(QString("Driver={SQL Server Native Client 10.0};Server=X.X.X.X;Database=/*DB*/;"));
    db.setUserName("sa");
    db.setPassword("/*password*/");

    if (!db.open()) {
        qDebug() << db.lastError().text();
    }
    else
    {
        qDebug() << "connected";
    }

But after about 7 sec it gives me this log :

[Microsoft][SQL Server Native Client 10.0]Named Pipes Provider: Could not open a connection to SQL Server [1326]. [Microsoft][SQL Server Native Client 10.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. [Microsoft][SQL Server Native Client 10.0]Login timeout expired QODBC3: Unable to connect

However server is up and running and the connectivity is ok and already tested with UDL file.

Note: the local connection works well

Upvotes: 0

Views: 625

Answers (1)

Sebastian Lange
Sebastian Lange

Reputation: 4029

Use these settings, having the user and pass in the dbname, please:

QString connectString = "Driver={SQL Server Native Client 10.0};"; // Driver can also be {SQL Server Native Client 11.0}
connectString.append("Server=SERVERHOSTNAME\\SQLINSTANCENAME;");   // Hostname,SQL-Server Instance
connectString.append("Database=SQLDBSCHEMA;");  // Schema
connectString.append("Uid=SQLUSER;");           // User
connectString.append("Pwd=SQLPASS;");           // Pass
db.setDatabaseName(connectString);
if(db.open())
{
    ui->statusBar->showMessage("Connected");
}else{
    ui->statusBar->showMessage("Not Connected");
}

or not using a full DSN

QString connectString = "Driver={SQL Server};"; // Driver is now {SQL Server}
connectString.append("Server=10.1.1.15,5171;"); // IP,Port
connectString.append("Database=SQLDBSCHEMA;");  // Schema
connectString.append("Uid=SQLUSER;");           // User
connectString.append("Pwd=SQLPASS;");           // Pass
db.setDatabaseName(connectString);
if(db.open())
{
    ui->statusBar->showMessage("Connected");
}else{
    ui->statusBar->showMessage("Not Connected");
}

Important for having a ip/port based connection is to have this type of connection enabled in the server configuration. Default one cannot connect using ip/port directly.

from https://wiki.qt.io/ODBC

Upvotes: 3

Related Questions