0
votes

I am trying to connect my qt application to ms sql database. I dont know server machine's IP addres and PORT number. I allready have Data Source Name in System DSN. Here is the sample of my code :

QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
db.setDatabaseName("DRIVER={SQL Server};SERVER={serverName};DATABASE=dbname;UID=username;PWD=password;WSID=.;Trusted_connection=yes");
bool ok = db.open();

    if(ok == true){
        qDebug()<<"connected";
    }
    else{
        qDebug()<<"not connected";
        qDebug()<<db.lastError().text();
    }

And i get this error :

[Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'xxx'. QODBC3: Unable to connect.

Any help will be appreciated.

1

1 Answers

1
votes

A few things here.

First, you either use windows authentication, or you use SQL authentication. Not both.

If your connection string specifies Trusted_connection=yes, or integrated security=SSPI, then you're using windows authentication.

If your connection string specifies uid=someuser; pwd=somepassword then you're using SQL auth.

Pick one.

Now, if you're using an ODBC DSN, then the DSN already specifies the driver and server, so you don't need that in your application connection string. Instead, you just tell the application which DSN to use.

Let's say you created your DSN and called it "MySqlServer". Then your code will look like this:

db.setDatabaseName("MySqlServer");

Now, if the DSN is set up to use windows authentication, that's all you need to do. On the other hand, if it's set up to use SQL authentication, then you can take the credentials already specified in the DSN, or set a username and password in your code:

db.setUserName("myUserName");
db.setPassword("myPassword");