Towhid
Towhid

Reputation: 2084

app.config file in C# for SQL Server 2005 in VS 2008

I have C# .net project with SQL Server 2008 written in Visual Studio 2008. There I used the following connection string to connect with SQL Server:

string connectionString = 
    @"server=HASIBPC\SQLEXPRESS; Integrated Security=SSPI; 
      database=XPHotelManagementDatabase";

But problem is every time I take my application from one computer to another computer I need to change the server in connectionString. I don't want to change this manually. I want this will change dynamically. How will I do that using app.config?

Upvotes: 3

Views: 1804

Answers (4)

Conrad Frix
Conrad Frix

Reputation: 52655

Aside from LOCALHOST and "." You can

  1. use "server = 127.0.0.1\SQLEXPRESS"

  2. Add an alias to the SQL Server Configuration Manager and use that in your string

  3. add 127.0.0.1 foo to your hostsfle and use it e.g. "server = FOO\SQLExpress"

  4. Mange the connection in the machine config

Upvotes: 0

It's actually me
It's actually me

Reputation: 502

Here is a sample;

Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\PressbyranDB.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True

Note that Data Source=.\SQLEXPRESS; attribute as your SQL Server and Server Instance name. Also, you do not need to restore your database from machine to machine if you use the AttachDbFilename= attribute.

Upvotes: 2

Adam Butler
Adam Butler

Reputation: 3037

You don't have to use app config to store a connection string - you could just pass a dynamically generated connection string to the SqlConnection constructor.

Upvotes: 1

Kelsey
Kelsey

Reputation: 47726

If the database is local with the application you can use LocalHost in your connection string assuming all other information is the same.

Eg:

string connectionString = @"server = LOCALHOST\SQLEXPRESS; Integrated Security = SSPI; database = XPHotelManagementDatabase";

Upvotes: 3

Related Questions