Mega Code Archive

 
Categories / C# Tutorial / ADO Net
 

Persist Adds

using System; using System.Data; using System.Data.SqlClient;     class PersistAdds     {         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"] = "Roy";                 newRow["lastname"] = "Beatty";                 newRow["titleofcourtesy"] = "Sir";                 newRow["city"] = "Birmingham";                 newRow["country"] = "UK";                 dt.Rows.Add(newRow);                 foreach (DataRow row in dt.Rows)                 {                     Console.WriteLine(row["firstname"]);                     Console.WriteLine(row["lastname"]);                     Console.WriteLine(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();             }         }     }