Aleksa Djuric
Aleksa Djuric

Reputation: 43

Connection string for SQL Server ( local database )

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

Upvotes: 4

Views: 14484

Answers (2)

Brian
Brian

Reputation: 5119

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.

Upvotes: 3

MLeblanc
MLeblanc

Reputation: 1884

Remove the last dot of the IP address.

"Data Source=127.0.0.1.;" +   

Should be:

"Data Source=127.0.0.1;" +

Upvotes: 2

Related Questions