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();
// 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(); }
Be the first to rate this post
Tags: learn asp.net, asp.net c# database connection, free source code
8/23/2008 9:04:44 PM