"Login failed for user" C# with SQLConnection

Lourens picture Lourens · Jan 28, 2013 · Viewed 66.6k times · Source

I've been trying to connect to my database (which is on the same computer as my code) through my C# code. The problem is I keep getting the "Login failed for user " "" error... I admit that my knowledge of connecting to databases is minimal and I've tried almost all the steps in other questions!

here's part of my code:

SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLServerConnection"].ConnectionString);
        SqlCommand command = connection.CreateCommand();
        command.CommandText = @"IF EXISTS
                            (
                              SELECT *
                              FROM user 
                              WHERE EMAILADRES = @email and WACHTWOORD = @password
                            ) SELECT CAST (1 as bit) 
                            ELSE
                              SELECT CAST(0 as bit)";
        command.Parameters.AddWithValue("email", email);
        command.Parameters.AddWithValue("password", password);


        connection.Open();
        object ReturnBool = command.ExecuteScalar();
        connection.Close();

and this is my connection string:

<add name="SQLServerConnection" connectionString="Server=localhost; Database=database1;uid=NT AUTHORITY\NETWORK SERVICE" />

Answer

daryal picture daryal · Jan 28, 2013

you need to change the connection string;

<add name="SQLServerConnection" connectionString="Server=localhost;Database=database1;Trusted_Connection=True;/>

if you are using windows authentication to connect to the local DB, you need to set Trusted_Connection=True; if you are using SQL server authentication, you need to declare User Id=myUsername; Password=myPassword;.