Add data to database using SqlDataAdapter : SqlDataAdapter « Database ADO.net « C# / C Sharp






Add data to database using SqlDataAdapter


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

class Class1{
      public static void Main() {
         SqlConnection thisConnection = new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI");

         SqlDataAdapter thisAdapter = new SqlDataAdapter( 
            "SELECT ID, FirstName FROM Employee", thisConnection);

         SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);

         DataSet thisDataSet = new DataSet();

         thisAdapter.Fill(thisDataSet, "Employee");

         Console.WriteLine("# rows before change: {0}",thisDataSet.Tables["Employee"].Rows.Count);

         DataRow thisRow = thisDataSet.Tables["Employee"].NewRow();
         thisRow["ID"] = "123";
         thisRow["FirstName"] = "Ltd";
         thisDataSet.Tables["Employee"].Rows.Add(thisRow);

         Console.WriteLine("# rows after change: {0}", thisDataSet.Tables["Employee"].Rows.Count);

         thisAdapter.Update(thisDataSet, "Employee");
      }
}


           
       








Related examples in the same category

1.Delete data from database table using SqlDataAdapter
2.Update database using the SqlDataAdapter