Search code examples
c#sql-serverauthenticationsqlconnection

SQLConnection connection error "Login failed for user server/guest"


I keep receiving a connection error. I know that the information is right, as I tried them out with SSMS now several times in the last few minutes, so the problem is in the C# connection string. According to various Google searches, the syntax is right, just it does not work.

try
{
    // Get the connection information.
    GetSQLConnectInfo(ref sConnect);

    // Formulate the connection string.
    String strConnect = String.Format("Server=myserver;Database=mydb;User Id=myusername;Password=mypassword;Trusted_Connection=yes;connection timeout=30");

    // DATABASE: Create the connection.
    SqlConnection oConnection = new SqlConnection(strConnect);
    oConnection.Open();
    if (ConnectionState.Open != oConnection.State)
        return false;

    return true;
}

catch
{
}

Error comes back with: Login failed for user 'myserver\Guest'. Error Code: -2146232060 Error Number: 18456

It would seem that judging by the error message, the Open method does not recognize the user name, as Open tries to use a guest account, which obviusly will not work.

Am I missing something? I am using SQL Server authentication.


Solution

  • Remove Trusted_Connection=yes. That will override your SQL Authentication (username/password) settings and try to log in as the user running the app.

    From the documentation:

    If the value of the Trusted_Connection key is "Yes", both the UID and PWD keys are ignored. Otherwise, the UID key has to be specified.