Requirements Testing

Web.Config Connection String Settings in .NET 2.0

We have been doing a lot of asp.net 2.0 development lately.  Here is how we are setting up the web.config file to hold our connection settings.  First, set your web.config file Connection String settings as follows:

<connectionStrings>
<add name="YourConnectionString" connectionString="Data Source=YourSQLServer;Initial Catalog=YourDatabase;User ID=YourUserID;Password=YourPassword" providerName="System.Data.SqlClient" />
</connectionStrings>

In your data access layer classes set the sqlconnection object to the web.config connection string thru the constructor. For VB.NET that is the class’s New() function.  In C# it is the function named the same as the class.  Below are both examples or download the C# version or VB.NET version directly.

Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI

Public Class DataAccess

Dim conn As New SqlConnection
Dim sql As String
Dim objSql As SqlCommand
Dim MyDataReader As SqlDataReader

Public Sub New()
If ConfigurationManager.ConnectionStrings("YourConnectionString") Is Nothing OrElse _
ConfigurationManager.ConnectionStrings("YourConnectionString").ConnectionString.Trim() = "" Then
Throw New Exception("Connection Error")
Else
conn.ConnectionString = ConfigurationManager.ConnectionStrings("YourConnectionString").ConnectionString
End If

End Sub

Public Function GetMSRP(ByVal productid As Int32) As String

Dim strUnitPrice As String = Nothing
sql = "SELECT UnitPrice FROM Products WHERE productid = @productid"
‘Set SQL OBJECT
objSql = New SqlCommand(sql, conn)
‘Add Parameters
objSql.Parameters.AddWithValue("@productid", productid)

Try
‘Open Connection
conn.Open()
‘Execute DataReader
MyDataReader = objSql.ExecuteReader
‘Store Values in String Variables
While (MyDataReader.Read())
strUnitPrice = MyDataReader.Item("UnitPrice")
End While
‘Close Connection
conn.Close()
Catch ex As Exception
‘TODO HANDLE EX
End Try
Return strUnitPrice
End Function

End Class

################### c# version

using Microsoft.VisualBasic;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
public class DataAccess {
   
    private SqlConnection conn = new SqlConnection();
   
    private string sql;
   
    private SqlCommand objSql;
   
    private SqlDataReader MyDataReader;
   
    public DataAccess() {
        if (((ConfigurationManager.ConnectionStrings("YourConnectionString") == null)
                    || _)) {
            ConfigurationManager.ConnectionStrings("YourConnectionString").ConnectionString.Trim() = "";
            throw new Exception("Connection Error");
        }
        else {
            conn.ConnectionString = ConfigurationManager.ConnectionStrings("YourConnectionString").ConnectionString;
        }
    }
   
    public string GetMSRP(Int32 productid) {
        string strUnitPrice = null;
        sql = "SELECT UnitPrice FROM Products WHERE productid = @productid";
        objSql = new SqlCommand(sql, conn);
        // Add Parameters
        objSql.Parameters.AddWithValue("@productid", productid);
        try {
            // Open Connection
            conn.Open();
            // Execute DataReader
            MyDataReader = objSql.ExecuteReader;
            // Store Values in String Variables
            while (MyDataReader.Read()) {
                strUnitPrice = MyDataReader.Item["UnitPrice"];
            }
            // Close Connection
            conn.Close();
        }
        catch (Exception ex) {
            // TODO HANDLE EX
        }
        return strUnitPrice;
    }
}

Written by Tim on February 13th, 2006 with 5 comments.
Read more articles on asp.net.



Related articles

5 comments

Read the comments left by other users below, or:

Get your own gravatar by visiting gravatar.com poker casino287
#1. March 28th, 2006, at 11:25 PM.

poker casino poker 813

Get your own gravatar by visiting gravatar.com Antonio
#2. March 31st, 2008, at 7:47 AM.

Thanx,this was very helpfull.

Get your own gravatar by visiting gravatar.com waltman
#3. June 3rd, 2008, at 1:17 AM.

Thanks — you guys rule!!!

Get your own gravatar by visiting gravatar.com jamil
#4. June 4th, 2008, at 6:59 PM.

your sample is good but leaves out few stuff.

Go to the MyProject page and select References. Click “Add” and go to the .NET tab and select System.Configuration.

Also, class has following imports
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Get your own gravatar by visiting gravatar.com jamil
#5. June 4th, 2008, at 7:52 PM.

I am sorry. I could not get your code to work. Keep getting connection could be opened or something like that.

Leave your comment...

If you want to leave your comment on this article, simply fill out the next form:




You can use these XHTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong> .