tags:

views:

112

answers:

4

Hi there,

I have a web project and a separate project for a class which contains a constant and I am thinking of adding a connection string. What is the best way for storing this?

Thanks

+1  A: 

I would advise against storing your connection string in a hard-coded constant. There are many problems with that, not the least of which you aren't actually able to "configure" your connection string for different environments. Having it hard coded makes it very difficult to test your code in one environment against a different database than your production environment, without having to recompile your code. There are also security concerns in regards to hard-coding configuration, particularly connection strings.

I recommend reading the following article...it should give you a good base about storing connection strings in the standard .NET way:

Connection Strings and Configuration Files (ADO.NET)

jrista
A: 

Put it in the settings file for the project. The settings file is merged into the .config file - and you get a class automatically built for you with accessors for the stuff in the settings file.

1800 INFORMATION
+3  A: 

Add a section to your web.config file called ConnectionStrings, as a child of the <configuration> element. An example might look like:

<connectionStrings>
    <add name="MyConnectionString" 
         connectionString="Server=myserver;Database=mydatabase;Uid=username;Pwd=password;"/>
</connectionStrings>

In your code, use the ConfigurationManager to access your connection strings. For example,

string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString();
womp
Don't forget to add reference in your library of System.Configuration.
Muhammad Akhtar
Yeah, I usually put in the fully qualified names of objects in my code examples so people have some idea of where they live. It's better to code without fully qualifying them though.
womp
+1  A: 

Add it to settings file. In Visual Studio, go to My Project -> Settings and add it there as (Connection String). You can access it this way: C# - properties.settings.default...; VB - My.Settings...

dipbhi