cc0
cc0

Reputation: 1950

ASP.NET MVC 2, re-use of SQL-Connection string

so I'm very very far from an expert on MVC or ASP.NET. I just want to make a few simple Controllers in C# at the moment, so I have the following question;

Right now I have the connection string used by the controller, -inside- the controller itself. Which is kind of silly when there are multiple controllers using the same string. I'd like to be able to change the connection string in just one place and have it affect all controllers.

Not knowing a lot about asp.net or the 'm' and 'v' part of MVC, what would be the best (and simplest) way of going about accomplishing just this?

I'd appreciate any input on this, examples would be great too.

Upvotes: 2

Views: 1747

Answers (2)

ten5peed
ten5peed

Reputation: 15890

Put it in your web.config file like so:

<connectionStrings>
    <add name="ConnectionName" connectionString="TheConnectionString" providerName="System.Data.SqlClient" />
</connectionStrings>

<connectionStrings> is just a child of the root <configuration> element.

Then you can read it like:

string myConnStr = ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;

HTHs, Charles

Upvotes: 2

Fabio Milheiro
Fabio Milheiro

Reputation: 8474

You may add a connection string to the web.config file like this:

<configuration>
  <appSettings>
    <add key="ConnectionString"
      value="server=localhost;database=Northwind;uid=sa;password=secret;"/>
  </appSettings>
  <system.web>
    <customErrors mode="Off"/>
  </system.web>
</configuration>

and use it in your code like this:

strConnection = ConfigurationSettings.AppSettings("ConnectionString") // <-----
sqlConn = New SqlConnection(strConnection)
sqlCmd = New SqlCommand("SELECT * FROM Customers WHERE " & "(CompanyName LIKE 'A%') OR (CompanyName LIKE 'B%')", sqlConn)

Notice the first line. This example is for VB but you should be able to do the same in C#.

The example is taken from this link http://www.dotnetjohn.com/articles.aspx?articleid=3, but there are tons of them everywhere.

Hope this helps.

Upvotes: 1

Related Questions