使用SqlDataAdapter提交数据到数据库

// 使用SqlDataAdapter提交数据到数据库

// PersistChanges.cs
using System;
using System.Data;
using System.Data.SqlClient;
namespace Ch13
{
    class PersistChanges
    {
        static void Main( string[] args)
        {
            string strConn = "server=.\\MSSQL2012;integrated security=true;database=Northwind";
            string qry = "select * from employees where country='UK'" ;
            string upd = "update employees set city=@city where employeeid=@empid";
            SqlConnection conn = new SqlConnection(strConn);
            try
            {
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand(qry, conn);
                DataSet ds = new DataSet();
                da.Fill(ds, "emp" );
                DataTable dt = ds.Tables[ "emp" ];
               
                // 对第一行进行操作
                DataRow row = dt.Rows[0];
                Console.WriteLine( "修改前" );
                Console.WriteLine( "{0} {1} {2} {3}"
                    , row[ "employeeid" ].ToString().PadRight(5)
                    , row[ "firstname" ].ToString().PadRight(10)
                    , row[ "lastname" ].ToString().PadRight(10)
                    , row[ "city" ]);
                // 修改第一行的city字段
                row[ "city" ] = "Wilmington" ;
                Console.WriteLine( "修改后" );               
                Console.WriteLine( "{0} {1} {2} {3}"
                    , row[ "employeeid" ].ToString().PadRight(5)
                    , row[ "firstname" ].ToString().PadRight(10)
                    , row[ "lastname" ].ToString().PadRight(10)
                    , row[ "city" ]);
                // 此时从数据库查看,并没有真正的更新到数据库
                
                SqlCommand cmd = new SqlCommand(upd, conn);
                // @city参数映射为city数据列。注意,没有指定数据表,但必须
                // 确保其类型和长度与最终所用数据表中的这一列兼容。
                // @city在默认情况下从数据表的当前版本中取值,也就是修改后的 Wilmington
                cmd.Parameters.Add( "@city" , SqlDbType.NVarChar, 15, "city" );
                // @empid参数映射到employeeid字段。
                // @empid必须从修改之前的版本中取值,也就是 5
                SqlParameter parm = cmd.Parameters.Add( "@empid" , SqlDbType.Int, 4, "employeeid" );
                parm.SourceVersion = DataRowVersion.Original;
                // 相当于使用下面的SQL更新表
                // update employees set city='Wilmington' where employeeid=5
                da.UpdateCommand = cmd;
                da.Update(ds, "emp" );
                // 此时从数据库查看,数据已更新到数据库
                
            }
            catch( Exception ex)
            {
                Console.WriteLine( "出错了:" + ex);
            }
            finally
            {
                conn.Close();
                Console.ReadLine();
            }
        }
    }
}
---------------------------------------
修改前
5     Steven     Buchanan   London
修改后
5     Steven     Buchanan   Wilmington
posted on 2013-08-23 21:58  伊利丹  阅读(320)  评论(0编辑  收藏  举报