微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

关于DataSet事务处理以及SqlDataAdapter四种用法

如果是直接执行sql语句时,事务很好处理,对于大多数的Erp应用,不能能用sql来处理数据,所以更新DataSet更为常用,更新单个的DataSet也非常简单,不需要事务的处理,给多个DataSet增加事务多数应用于分布式的程序代码中,下面为在Webservice中更新Winform传递过来的经过压缩的数据集的事务处理代码,多个DataSet 情况。
/// <summary>
    /// 更新经过压缩的DataSet
    /// </summary>
    /// <param >环境变量</param>
    /// <param >二进制的DataSet</param>
    /// <returns>出现异常,返回一个错误信息</returns>
        public object UpdataSet(object[] env,byte[] byt)
    {
        object info = null;
        sqlConnection sqlconn = null;
        //定义事务
        sqlTransaction transaction = null;
        DataSet ds = null;
        try
        {
            ds = md.BytesToDs(byt);
            string Url = "数据库连接语名";
            sqlconn = new sqlConnection(Url);
            sqlconn.open();
            transaction = sqlconn.BeginTransaction(IsolationLevel.ReadCommitted,"transname");//实例化事务
            sqlDataAdapter adapter;
            sqlCommandBuilder objCommandBuilder;
            for (int i = 0; i < ds.Tables.Count; i++)
            {
                adapter = new sqlDataAdapter("select * from " + ds.Tables[i].TableName + " where 2>3",sqlconn);//传统用法
                objCommandBuilder = new sqlCommandBuilder(adapter);
                //开始挂起
                //挂起操作
                adapter.DeleteCommand = new sqlCommand("...删除语句..",sqlconn,transaction);
                //adapter的增删查改可以与事务一起用,注意这里没有实例sqlCommand对象所以new sqlCommand
                adapter.InsertCommand = new sqlCommand("............",transaction);
                adapter.UpdateCommand = new sqlCommand(".............",transaction);
                adapter.SelectCommand = new sqlCommand("select * from " + ds.Tables[i].TableName + " where 2>3",transaction);
                //以上是adapter的新用法,new sqlCommand后面写sql语句,sqlConnection,还可以写事务...就不用实例sqlCommand对象
                //没有实例sqlCommand对象所以获取
                adapter.DeleteCommand = objCommandBuilder.GetDeleteCommand();
                adapter.InsertCommand = objCommandBuilder.GetInsertCommand();
                adapter.UpdateCommand = objCommandBuilder.GetUpdateCommand();
                objCommandBuilder.DataAdapter.Update(ds,ds.Tables[i].TableName.ToString());//
                
            }
            transaction.Commit();//无误后提交事务
            sqlconn.Close();
        }
        catch (Exception err)
        {
            Console.Out.WriteLine("存盘时发生错误:" + err.Message);
            info = "存盘时发生错误:" + err.Message;
            //事务回滚
            transaction.Rollback();
        }
        finally
        {
            if (sqlconn != null)
            {
                sqlconn.Close();
            }
        }
        return info;
    }
 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐