关于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("............", sqlconn, transaction);
adapter.UpdateCommand = new SqlCommand(".............", sqlconn, transaction);
adapter.SelectCommand = new SqlCommand("select * from " + ds.Tables[i].TableName + " where 2>3", sqlconn, 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;
}