1

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

4 Answers 4

4

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Don't forget to add reference in your library of System.Configuration.
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.
2

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...

Comments

1

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)

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.