SqlDataAdapter.InsertCommand : SqlDataAdapter « System.Data.SqlClient « C# / C Sharp by API






SqlDataAdapter.InsertCommand

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

class MainClass
{
   static void Main(string[] args)
   {
      string connString = @"server = .\sqlexpress;integrated security = true;database = northwind";

      string qry = @"select * from employees where country = 'UK'";

      string ins = @"insert into employees(firstname,lastname,titleofcourtesy,city,country)
                                    values(@firstname,@lastname,@titleofcourtesy,@city,@country)";

      SqlConnection conn = new SqlConnection(connString);

      try
      {
         SqlDataAdapter da = new SqlDataAdapter();
         da.SelectCommand = new SqlCommand(qry, conn);

         DataSet ds = new DataSet();
         da.Fill(ds, "employees");

         DataTable dt = ds.Tables["employees"];

         DataRow newRow = dt.NewRow();
         newRow["firstname"] = "R";
         newRow["lastname"] = "B";
         newRow["titleofcourtesy"] = "Sir";
         newRow["city"] = "B";
         newRow["country"] = "UK";
         dt.Rows.Add(newRow);

         foreach (DataRow row in dt.Rows)
         {
            Console.WriteLine(
               "{0} {1} {2}",
               row["firstname"].ToString().PadRight(15),
               row["lastname"].ToString().PadLeft(25),
               row["city"]);
         }

         SqlCommand cmd = new SqlCommand(ins, conn);
         cmd.Parameters.Add("@firstname",SqlDbType.NVarChar, 10,"firstname");
         cmd.Parameters.Add("@lastname",SqlDbType.NVarChar,20,"lastname");
         cmd.Parameters.Add("@titleofcourtesy",SqlDbType.NVarChar,25,"titleofcourtesy");
         cmd.Parameters.Add("@city",SqlDbType.NVarChar,15,"city");
         cmd.Parameters.Add("@country",SqlDbType.NVarChar,15,"country");
         da.InsertCommand = cmd;
         da.Update(ds, "employees");
      }
      catch(Exception e)
      {
         Console.WriteLine("Error: " + e);
      }
      finally
      {
         conn.Close();
      }
   }
}

   
  








Related examples in the same category

1.new SqlDataAdapter
2.SqlDataAdapter.Fill
3.SqlDataAdapter.DeleteCommand
4.SqlDataAdapter.RowUpdated
5.SqlDataAdapter.RowUpdating
6.SqlDataAdapter.SelectCommand
7.SqlDataAdapter.SelectCommand.Parameters.Add
8.SqlDataAdapter.TableMappings
9.SqlDataAdapter.TableMappings.Add
10.SqlDataAdapter.Update
11.SqlDataAdapter.UpdateCommand