首页 > 编程 > .NET > 正文

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

2024-07-10 13:04:58
字体:
来源:转载
供稿:网友
提供一个数据服务类,调用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 [email protected]",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),不过程序员的控制能力要强一些了。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表