SqlDataAdapter的InsertCommand属性
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("Server=zhuobin;uid=sa;pwd=zhuobin;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)";
try
{
//create the Adapter
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(qry,conn);
//create the DataSet
DataSet ds = new DataSet();
da.Fill(ds,"employees");
//get the table reference
DataTable dt = ds.Tables["employees"];
//Add a new row
DataRow newRow = dt.NewRow();
newRow["Firstname"] = "Zhuo";
newRow["lastname"] = "bin";
newRow["titleofcourtesy"] = "Sir";
newRow["city"] = "Tengzhou";
newRow["country"] = "China";
dt.Rows.Add(newRow);
//display the data
foreach (DataRow row in dt.Rows)
{
Console.WriteLine("{0}{1}{2}",row["firstname"].ToString().PadRight(15),row["lastname"].ToString().PadLeft(25),row["city"]);
}
//insert into employees
//create command
SqlCommand cmd = new SqlCommand(ins,conn);
//map parameters
cmd.Parameters.Add("@firstname",SqlDbType.NVarChar,10,"firstname");
cmd.Parameters.Add("@lastname",SqlDbType.NVarChar,10,"lastname");
cmd.Parameters.Add("@titleofcourtesy",SqlDbType.NVarChar,10,"titleofcourtesy");
cmd.Parameters.Add("@city",SqlDbType.NVarChar,15,"city");
cmd.Parameters.Add("@country",SqlDbType.NVarChar,15,"country");
//insert into employees
da.InsertCommand = cmd;
da.Update(ds,"employees");
}
catch (SqlException ex)
{
Console.WriteLine("The error:{0}", ex.Message);
}
finally
{
conn.Close();
}
Console.ReadLine();
}
}
}