ASP.Net C# Database Connection

by top54u.com 07 Feb, 2008
Spotlight.....

ASP.Net Web.config settings to define connection string for C# Database Connection:
Add the following string in <configuration> section of web.config file:

 

<appSettings>
       <add key="ConnectionString" value="Data Source=.; Initial Catalog = YOUR SQL DATABASE NAME; User ID = YOUR USERNAME;Password = YOUR PASSWORD;"/>
</appSettings>

 

In the value attribute:

Data Source:
You can use the IP address of the web server configured with SQL server or where you have hosted your web site. Mostly in Data Source field localhost is used.

Initial Catalog:
Enter the name of the SQL Database.

User ID and Password:
Enter the MS SQL Server authenticated username and password.

 

Import Namespaces for SQL Connection: 

using System.Data;
using System.Data.SqlClient;

 

C# Code to access the database connection:

 

// string variable to store the connection string
// defined in appsettings section of web.config file.
string connStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();

// object created for SqlConnection Class.
SqlConnection mySQLconnection = new SqlConnection(connStr);

// if condition that can be used to check the sql connection
// whether it is already open or not.
if (mySQLconnection.State == ConnectionState.Closed)
{
    mySQLconnection.Open();
}

// message string just to display the sql connection state.
Response.Write("ASP.Net 2.0 SQL Database Connection State: <b>" + mySQLconnection.State + "</b>");

// if condition that can be used to check the sql connection
// if it is open then close it.
if (mySQLconnection.State == ConnectionState.Open)
{
    mySQLconnection.Close();
}

 

Spotlight.....

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

8/23/2008 9:04:44 PM

OUR SPONSORS[+ advertise here]
related videos.....
recent posts.....
top54u ezines.....