I am making an application to connect to a local SQL Server database, and I am using the following method to create the connection string and test for exceptions.
public void connect(string user, string password, string server, string database)
{
connectString = "user id=" + user + ";" +
"password=" + password + ";" +
"server=" + server + ";" +
"Trusted_Connection=yes;" +
"database=" + database + ";" +
"connection timeout=5";
myConnection = new SqlConnection(connectString);
try
{
myConnection.Open();
isConnected = true;
}
catch (SqlException)
{
isConnected = false;
}
catch (InvalidOperationException)
{
isConnected = false;
}
}
From my research there should be an exception thrown if the connection cannot be opened, but if I pass nonsense credentials or empty strings no exception is thrown. If I pass in correct information I am able to connect and use the connection string to pull in data. With the bad connection string I get an exception later when trying to fill a SqlDataAdapter with the data.
Also, with the nonsense connection strings myConnection.State is open when I debug and check that.
Is there a problem with my understanding of how the exception catching should work? Am I correct in thinking that the SqlConnection State should not be open when I am unable to connect to the database because of a bad credentials?