4

I added a local database to my application in Visual Studio:

database

and I need connection string for it - here it is:

SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=127.0.0.1.;" +
                        "Initial Catalog=Filter;" +
                        "Integrated Security=SSPI;";

conn.Open();

When I run that block of code, the whole UI thread stops, like infinite for loop. What is wrong with my connection string?

I'm working with Windows Forms, C#, .NET Framework version 4.5.1

1
  • 1
    Going by the screenshot it looks like you're trying to connect to a database file (.mdf) and not to a server instance. if Data Source=<yourcomputername> doesn't work then try putting the path to the mdf file. E.g. Data Source=C:\Data\Filters.mdf. I'm guessing that the reason the UI thread stops is because the default connection timeout is 30 seconds, so the connection has 30 seconds to respond before .net throws an exception. Commented Nov 21, 2018 at 21:03

2 Answers 2

3

Part of your problem is you have a trailing '.' in your IP address. Remove that like so:

"Data Source=127.0.0.1;" +
"Initial Catalog=Filter;" +
"Integrated Security=SSPI;";

Also, I would strongly suggest that you wrap your connection object in a using statement like this:

using (SqlConnection conn = new SqlConnection())
{ 
   conn.ConnectionString =
   "Data Source=127.0.0.1.;" +
   "Initial Catalog=Filter;" +
   "Integrated Security=SSPI;";

    conn.Open();
}

Lastly, define your connection in a string and pass it into your SqlConnection object when you instantiate it, like this:

string sqlConnection = "Data Source=127.0.0.1;Initial Catalog=Filter;Integrated Security=SSPI;"

using (SqlConnection conn = new SqlConnection(sqlConnection)
{
   conn.Open();
}

This approach does several things for you:

  1. It makes your code much, much easier to read, and clean.
  2. It ensures that your connection object will get handled by Dispose even if there is an exception thrown in the using block.
  3. It is just a good habit to get into early.

More on the SqlConnection class here, and more on using can be found here.

Sign up to request clarification or add additional context in comments.

1 Comment

See the comment above, in your original question. Are you pointing to the right (or any) .mdf file?
2

Remove the last dot of the IP address.

"Data Source=127.0.0.1.;" +   

Should be:

"Data Source=127.0.0.1;" +

1 Comment

Make sure sql server is up and running and you can connect to the database using windows authentication with SSMS. If it works, see connectionstrings.com/sql-server for proper syntax

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.