修改数据集中的数据

注意:

对数据集所做的变化不会自动保存在数据库中。为了把这些变化保存到数据库中,需要再次连接到数据库,显式地完成更新。

实例:修改数据集中的数据表

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace ModifyDataTable
{
    class Program
    {
        static void Main(string[] args)
        {
            string connString = @"
            server = .;
            integrated security =true;
            database =northwind";

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

            SqlConnection conn = new SqlConnection(connString);

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

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

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

                //FirstName column should be nullable
                dt.Columns["firstname"].AllowDBNull = true;

                //modify city in first row
                dt.Rows[0]["city"] = "Wilmington";

                //add a row
                DataRow newRow = dt.NewRow();
                newRow["firstname"] = "Tan";
                newRow["lastname"] = "Ding";
                newRow["titleofcourtesy"] = "Sir";
                newRow["city"] = "shenzheng";
                newRow["country"] = "CN";
                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"]);
                }
            }
            catch (SqlException e)
            {
                Console.WriteLine("Error: " + e);
            }
            finally
            {
                conn.Close();
            }
            Console.ReadKey();
        }
    }
}

给数据表添加一个新行:

 //add a row
                DataRow newRow = dt.NewRow();
                newRow["firstname"] = "Tan";
                newRow["lastname"] = "Ding";
                newRow["titleofcourtesy"] = "Sir";
                newRow["city"] = "shenzheng";
                newRow["country"] = "CN";
                dt.Rows.Add(newRow);

NewRow方法创建了一个数据行(一个System.Data.DataRow实例)。然后使用这个DataRow对象的索引器给其列赋值。最后,在DataTable对象的Rows属性(表示行集合)上调用Add方法,把新行添加到数据表中。

注意,没有提供EmployeeID列的值,因为它是IDENTITY列。如果打算把变化保存到数据库,SQL Server会自动为这个字段提供值。

 

转载于:https://www.cnblogs.com/tanding/archive/2012/07/20/2601361.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值