把数据集的变化保存到数据源中

实例:

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

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

            string qry = @"select * from employees where country ='UK'";
            string upd = @"update employees set city=@city where employeeid =@employeeid";

            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"];
                dt.Rows[0]["city"] = "luoding";

                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(upd, conn);
                cmd.Parameters.Add("@city", SqlDbType.NVarChar, 15, "city");
                SqlParameter parm = cmd.Parameters.Add("@employeeid", SqlDbType.Int, 4, "employeeid");
                parm.SourceVersion = DataRowVersion.Original;

                da.UpdateCommand = cmd;
                da.Update(ds, "employees");
            }
            catch (SqlException e)
            {
                Console.WriteLine("Error: " + e);
            }
            finally
            {
                conn.Close();
            }
            Console.ReadKey();
        }
    }
}

示例说明
添加一个UPDATE语句,把原查询字符串变量的名称sql改为upd,以便与这个语句区分开来。

            string upd = @"update employees set city=@city where employeeid =@employeeid";

创建命令,使用更新的SQL变量upd

    SqlCommand cmd = new SqlCommand(upd, conn);

接着配置命令参数。@city参数映射为city数据列。注意,没有指定数据表,但必须确保其类型和长度与最终所用数据表中的这一列兼容。

     cmd.Parameters.Add("@city", SqlDbType.NVarChar, 15, "city");

下一步,配置@employeeid参数,把它映射到employeeid数据列上。@city在默认情况下从数据表的当前版本中提取值,而@employeeid必须从修改前的版本中提取值。因为没有修改任何雇员ID,但最好为主键指定原来的版本,这样,如果主键发生变化,就可以在数据库表中访问正确的行。还要注意保存Add方法返回的引用,以便设置其SourceVersion属性。@city不需要其他处理,所以不必保存对它的引用。

SqlParameter parm = cmd.Parameters.Add("@employeeid", SqlDbType.Int, 4, "employeeid");

最后,用命令设置数据适配器的UpdateCommand参数来更新Employees表,该命令是在调用Update方法时数据适配器执行的SQL。接着在数据适配器上调用Update方法,把变化保存到数据库中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值