Pages

Friday, 17 February 2012

ASP Code to Make a Database Connection(C# code.)

In order to make a database Connection First of all we need to set Connection string,Here the connection may set by a connection string or by the database name..And a query which retrieves the data from the databse or send data to the tables in the databse,The following code estblishes such an example for databse connectivity in  ASP.NET 2.0 usin C# code..

using System.Data.SqlClient ;

protected void Page_Load(object sender, EventArgs e)
{
        //Establishes Dtabse Connection in a string 
        string sp1  = ConfigurationManager.ConnectionStrings[ "ConnectionString" ].ConnectionString ;
        //Connects to the Server database
        SqlConnection con  =  new SqlConnection(sp1) ;
        //Openss the Connection
        con.Open();
        //Sets the Query to fetch data from databse,this may insert,delete or update query
        string query  =  "select * from maintable where name='alfred'" ;
        SqlCommand cmd  =  new SqlCommand(query, con) ;
        //If the query is reader then SqldataReader,if update or delete then it must be DataAdapter and                      
        statement become cmd.ExecuitNonQuery
        SqlDataReader dr  =  cmd.ExecuteReader() ;
        if(dr.Resd())
        {
               Label1.Text  =  "success" ;
        }
        else
        {
               Label1.Tex t  =  "failed" ;
         }
 }


No comments:

Post a Comment