Sunday 20 October 2013

How to Update data into SQL Server using C#.net

This is simple task which can be accomplished with below code. Below code is useful to Update data into SQL Server database using C#.

    public void UpdateContact_OnClick(object sender, EventArgs e)
    {
       string myUpdateCommand = @"Update Contact set Name=@name, EmailID=@emailid, Mobile=@mobile, LandLine=@landline, WebSite=@website, Address=@address where ID=@ID" ;

        SqlConnection connection = new SqlConnection("Data Source=(local); Initial Catalog = DataBaseName; Integrated Security=SSPI");
        SqlCommand cmd = new SqlCommand(myUpdateCommand , connection );
        cmd.Parameters.AddWithValue("@name", tbName.Text);
        cmd.Parameters.AddWithValue("@emailid", tbEmailID.Text);
        cmd.Parameters.AddWithValue("@mobile", tbMobile.Text);
        cmd.Parameters.AddWithValue("@landline", tbLandLine.Text);
        cmd.Parameters.AddWithValue("@website", tbWebSite.Text);
        cmd.Parameters.AddWithValue("@address", tbAddress.Text);
        cmd.Parameters.AddWithValue("@ID", Convert.ToInt32( tbID.Text));
        try
        {
            connection .Open();
            cmd.ExecuteNonQuery();
         }
         catch(Exception e)
        { }
        finally
        {
           connection .Close();
         }
    }


Connection string's options :
  •   Integrated Security=SSPI; – This means we want to connect using Windows authentication.
  •  Initial Catalog=DataBaseName; – This means the database we want to first connect to is named “DataBaseName”.
  •  Data Source=(local); – This means that we want to connect to the SQL Server instance located on the local machine.

No comments:

Post a Comment

Total Pageviews