Code

SqlDataAdapter的InsertCommand属性

 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();         
        }
    }
}

相关文章:

  • 2022-12-23
  • 2022-02-26
  • 2022-12-23
  • 2021-05-21
  • 2022-01-23
猜你喜欢
  • 2021-09-14
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-03
  • 2022-12-23
相关资源
相似解决方案