Using connection strings from web.config in ASP.NET v2.0

ASP.NET v2.0 has a couple new ways to reference connection strings stored in the web.config or machine.config file.

A typical web.config file in v2.0 could have the following section which is placed directly under the root <configuration> section.

<connectionStrings>
    <
remove name="LocalSqlServer"
/>
    <
add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"
/>
    <add name="MainConnStr" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|main.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>

connectionStrings>
    <
remove name="LocalSqlServer"
/>
    <
add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"
/>
    <add name="MainConnStr" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|main.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>

You can reference this directly from code using:

[C#]
string connStr = ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;

[VB]
Dim connStr As String = ConfigurationManager.ConnectionStrings("MainConnStr").ConnectionString

Note that the namespace for this is System.Configuration so for a console application the full namespace is required.


Or you can reference this declaratively within the ConnectionString property of a SqlDataSource:

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
  ConnectionString="<%$ ConnectionStrings:MainConnStr %>"
  SelectCommand="SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors]"
/>

25 Comments

  • "Or you can reference this declaratively within the ConnectionString property of a SqlDataSource"

    Are you sure? I get the error: The AccessDataSource ConnectionString property cannot be set, it is automatically generated.




  • if i upload a folder name "testweb" which has by default configurations of "web.config" and in that i have a simple page "abc.aspx" then have gridview name "grid" bounded with access db naming "db.mdf" via acccess datasource name "src"
    will the above situation needs some changes in web.config? if after making access db on server my server gives an ODBC connection string ,then where should i deploy this ODBC thing ?
    Please help me i am upset with it , i am good at ASP and C# coding but the above problem of deploying the ASP web with access database is making me frustrated

  • Hi Usman. Rather than using an ODCB connection, use just a direct connection to the access database (http://www.connectionstrings.com/access-2007). If you use a relative path then it will work when you deploy to the web server without needing to transform the web.config doc.

  • if i upload a folder name "testweb" which has by default configurations of "web.config" and in that i have a simple page "abc.aspx" then have gridview name "grid" bounded with access db naming "db.mdf" via acccess datasource name "src"

    will the above situation needs some changes in web.config? if after making access db on server my server gives an ODBC connection string ,then where should i deploy this ODBC thing ?

    Please help me i am upset with it , i am good at ASP and C# coding but the above problem of deploying the ASP web with access database is making me frustrated

  • Hi I,

    The trick is to not use ODBC. Instead you can use OLEDB which is a lot better and is xcopyable. Find the connection string that you need from http://www.connectionstrings.com/ and you can use that in your web.config file.

    You mentioned a mdf file. That assumes that you're using sql user instancing, which isn't installed by default. The best way to do this (usually) is to actually create the database on sql server itself and then use a connection string to that instance. Using the path on disk is only supported with some installs of sql express.

  • Is there an easy way to encrypt connection strings in a web config file?

    Thanks in advance

  • Is there an easy way to encrypt connection strings in a web config file?

    Thanks in advance

  • Hi M-Nimal,

    Depends on how you define easy. :) Actually it's not too bad. The kicker is that the encrypted key depends on a windows machine key, so you have 2 options. A) save the web.config file to the server first and then encrypt it while on the server. It's only useful on that server. B) export the machinekey to another location and then it will work between servers (necessary on a webfarm).

    The tool to do this is aspnet_regiis. I don't have a good proven doc to point you to but you can start with this: http://www.google.com/search?q=aspnet_regiis+encrypt+connection+string

    My own blog post from years ago turns up on the first page, but it's so old now that I didn't point directly to it.

  • What will be the ConnectionString for connecting a MS-Access database.?

  • The thesmartchamp. The best resource for that is http://www.connectionstrings.com/

  • Is there a way to set it dynamically, eg. ConnectionString=''? This will be useful for apps running on multiple dbs and change based on login.

  • Hi Conrad,

    Yes, check out this link on expression builders: http://www.beansoftware.com/ASP.NET-Tutorials/Expression-Builder.aspx. That should allow you to do what you're talking about.

  • HAI,
    THIS IS MY CONECTION STRING. BUT IT SI NOT WORKING PRPERLY.PLEASE CHECK IT OUT.

    MY CONNECTION STRING IS SQLCONNECTION CON= NEW SQL CONNECTION("SEVER=ABC;SOURCE="C:\\MYDOCUMENTS\\FUN2IN.SDF";INTEGRATED SECURITY =TRUE");.

  • Hi Suda,

    Here's a good list of connection string options for SQL CE: http://www.connectionstrings.com/sql-server-2005-ce. Be sure to confirm that your app pool has write access to the c:\mydocuments folders too.

    If that doesn't work, please explain further what issues you're running into.

  • access connection string is
    rovider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;

  • Hi Sankari,

    Happy New Year to you. Sorry for the delay.

    What are the details of your 500 error? There are multiple possible causes which the 500 error details will hopefully point in the right direction.

    One guess I would have is that your login database has more than 4 columns. If you name the query then it can handle schema changes in the future. For example: insert into login (name, password, password2) values (...). That way it doesn't depend on exactly 4 columns in that exact order.

    Also as a side it would be worth considering parameterizing your values to prevent sql injection attacks. This search has some good links on that: http://www.bing.com/search?q=parameterizing+sql+asp.net

  • Hello,

    I have read the article and comments. I want to know more about connection strings for connecting with MySQL Database.. I have my Database in MySql and want to integrate/ use it in my ASP.NET v2.0 application.
    Can anyone tell how to do it?
    Please reply.

    Regds
    an23in@sify.com

  • Hi Amit,

    The connection strings for mySql can be found here: http://www.connectionstrings.com/mysql. This page has good details on the .NET MySql connector: http://www.connectionstrings.com/Providers/mysql-connector-net-mysqlconnection.

  • string constr = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
    MySqlConnection con = new MySqlConnection(constr);
    its not working

  • @deepti. What error do you get? I would check connectionstring.com to confirm that your mysql connection string is correct and make sure that you have any necessary mysql drivers installed on your server.

  • i used the following connection string






    I got the following eror;

    Format of the initialization string does not conform to specification starting at index 0.

    my code is as follows;

    'Loading datagridview
    Dim cn As SqlConnection
    Dim cmdgetall As SqlCommand
    Dim adallinfo As SqlDataAdapter
    Dim STRSQL As String
    'initialise objects
    cn = New SqlConnection("ApplicationServices")
    adallinfo = New SqlDataAdapter()
    m_dswork = New DataSet()

    'set up command
    STRSQL = "SELECT * FROM BIODATA"
    cmdgetall = New SqlCommand(STRSQL, cn)
    adallinfo.SelectCommand = cmdgetall

    'set up mappings
    adallinfo.TableMappings.Add("Table", "BIODATA")

    'fill dataset
    cn.Open()
    adallinfo.Fill(m_dswork)
    cn.Close()

    'set up column objects for easy access
    Dim colstud As DataColumn
    colstud = m_dswork.Tables("BIODATA").Columns("BIODATA_Title")



    'BIND TABLE TO GRID
    GridView1.DataSource = m_dswork
    GridView1.DataMember = "BIODATA"
    GridView1.DataBind()
    GridView1.DataMember = ""
    GridView1.DataSource = Nothing
    End Sub

    please what do i do to correct the error?

  • Hi Samuel,

    Try changing this line:

    cn = New SqlConnection("ApplicationServices")

    to:

    cn = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString)

  • this message is very help, the information on msdn is obscure.

  • static string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;

    SqlConnection con = new SqlConnection(conStr);

Comments have been disabled for this content.