Sunday 20 October 2013

How to Insert data into sql server using C#.net

This is simple task which can be accomplished with below code. Below code is useful to insert data into SQL Server database using C#. I wrote code in 2 ways in which second way is preferred by many developers.

Method 1 :

    public void InsertContact_OnClick(object sender, EventArgs e)
    {
        string myInsertCommand = @"Insert into Contact (Name, EmailID, Mobile, LandLine, WebSite, Address) values( tbName.TexttbEmailID.TexttbMobile.Text, tbLandLine.Text,  tbWebSite.Text,  tbAddress.Text )";

        SqlConnection connection = new SqlConnection("Data Source=(local); Initial Catalog=DataBaseName; Integrated Security=SSPI");
        SqlCommand cmd = new SqlCommand(myInsertCommand, connection );
        try
        {
            connection .Open();
            cmd.ExecuteNonQuery();
         }
         catch(Exception e)
        { }
        finally
        {
           connection .Close();
         }
    }


Method 2 :

    public void InsertContact_OnClick(object sender, EventArgs e)
    {
        string myInsertCommand = @"Insert into Contact (Name, EmailID, Mobile, LandLine, WebSite, Address) values(@name, @emailid, @mobile, @landline, @website, @address)";

        SqlConnection connection = new SqlConnection("Data Source=(local); Initial Catalog=DataBaseName; Integrated Security=SSPI");
        SqlCommand cmd = new SqlCommand(myInsertCommand, 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);
        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