用ado.net进行分布式程序设计更新数据库

80酷酷网    80kuku.com

  ado|程序|分布式|设计|数据|数据库提供一个数据服务类,调用GetDataSet就得到需要的DataSet,然后在用户界面进行修改,最后调用SaveDate就可以把未定的更改保存到数据库。
using System;
using System.Data ;
using System.Data.SqlClient ;

namespace AsterDnet.DataBind
{
    /// <summary>
    /// Summary description for GetData.
    /// </summary>
    public class TestData
    {
        private SqlDataAdapter da;    
        public TestData()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        public  DataSet GetDataSet()
        {
            
            string strConn="data source=ASTERDNET;initial catalog=Test;integrated security=SSPI;persist security info=False;user id=sa;workstation id=ASTERDNET;packet size=4096";
            SqlConnection conn=new SqlConnection(strConn);
            conn.Open();
            DataSet ds=new DataSet();

            SqlParameter workParam=new  SqlParameter();
            da=new SqlDataAdapter();
            //Build the select Command
            da.SelectCommand =new SqlCommand("select * from Education ",conn);
            da.Fill(ds,"Education");
            

            // Build the insert Command
            da.InsertCommand = new SqlCommand("Insert into Education (ID, Education) VALUES (ID, Education)", conn);

            workParam = da.InsertCommand.Parameters.Add("ID", SqlDbType.Int);
            workParam.SourceColumn = "ID";
            workParam.SourceVersion = DataRowVersion.Current;

            workParam = da.InsertCommand.Parameters.Add("Education", SqlDbType.NChar, 50);
            workParam.SourceVersion = DataRowVersion.Current;
            workParam.SourceColumn = "Education";

            // Build the update command
            da.UpdateCommand = new SqlCommand("Update Education Set Education = Education WHERE ID = ID" , conn);

            workParam = da.UpdateCommand.Parameters.Add("ID", SqlDbType.Int);
            workParam.SourceColumn = "ID";
            workParam.SourceVersion = DataRowVersion.Original;

            workParam = da.UpdateCommand.Parameters.Add("Education", SqlDbType.NChar, 50);
            workParam.SourceVersion = DataRowVersion.Current;
            workParam.SourceColumn = "Education";

            //Build the delete command
            da.DeleteCommand =new SqlCommand("delete from Education where id=ID",conn);
            workParam=da.DeleteCommand.Parameters.Add("ID",SqlDbType.Int );
            workParam.SourceColumn ="ID";
            workParam.SourceVersion =DataRowVersion.Original;

            return ds;
        }
        //save the change dataset
        public void SaveDate(DataSet dataSet,string tableName)
        {
            da.Update(dataSet,tableName);
        }

    }
}

例中我建立了一个Test的数据库,数据库中建立一个Education的表,表中建立了两个字段ID(int),Education(char),在rc3中通过。

感觉没有vb6.0用ado2.5中那么方便(只要设置ActiveConnection,然后update就一切搞定,现在要自己写如何更新的SqlCommand),不过程序员的控制能力要强一些了。

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: