Connection Strings Without Web Config in Asp.Net

In this post, I am writing how to employ and utilise Asp.Net Connection Strings in when you don’t have the all-important Web.Config file at your disposal and you are disabled from using the Asp.Net ConfigurationManager class to establish the connection string.

Please review the link below to ensure you are using right Connection String format fitting your development environment and SQL instance.

Reference: http://www.connectionstrings.com/sql-server-2008

For establishing SQL Server Connection, running SQL Query / Stored Procedure you would require a Connection String. The code below uses a declarative connection string where Web.Config is not available.


Dim SqlConnectionString As String = "Server=SQLSERVER;Database=DB;User ID=Username;Password=password"
Dim ConnStringSettingObj As ConnectionStringSettings = New ConnectionStringSettings("constr", SqlConnectionString)

Dim path As String = ConnStringSettingObj.ConnectionString
Dim conn As SqlConnection = New SqlConnection(path)

Dim cmdText As String = "StoredProcedure_OR_SQL_Query"
Dim cmd As SqlCommand = New SqlCommand(cmdText, conn)

cmd.CommandType = CommandType.StoredProcedure
Dim _Param As SqlParameter = New SqlParameter("_SqlArgumentIfAny", SqlDbType.VarChar)
_Param.Value = "something"

cmd.Parameters.Add(_Param)

' If data return is required / otherwise ignore
Dim adaptr As SqlDataAdapter
Dim ds As New DataSet

Try
conn.Open()
adaptr = New SqlDataAdapter(cmd)
adaptr.Fill(ds)
Catch ex As Exception
Throw New ConfigurationErrorsException
Finally
conn.Close()
End Try

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s