有一个数据操作层的函数不懂.

来源:百度知道 编辑:UC知道 时间:2024/09/21 05:50:43
public bool ExecuteSQL(String[] SqlStrings)
{
bool success = true;
Open();
SqlCommand cmd = new SqlCommand();
SqlTransaction trans = Connection.BeginTransaction(); //尤其是这.最好同时给个整体分析.
cmd.Connection = Connection;
cmd.Transaction = trans;
try
{
foreach (String str in SqlStrings)
{
cmd.CommandText = str;
cmd.ExecuteNonQuery();
}
trans.Commit();//尤其是这
}
catch
{
success = false;
trans.Rollback();
}
finally
{
Close();
}
return success;
}

public bool ExecuteSQL(String[] SqlStrings)
{
bool success = true;
Open();
SqlCommand cmd = new SqlCommand();

//在Connection上启用事务,并返回事务对象。BeginTransaction 是对应SQL的BEGIN TRANSACTION的实现。
SqlTransaction trans = Connection.BeginTransaction(); //尤其是这.最好同时给个整体分析.

//将SqlCommand对象的数据库连接指定为Connection
cmd.Connection = Connection;
//把事务对象,赋值给cmd。
cmd.Transaction = trans;
try
{
foreach (String str in SqlStrings)
{
cmd.CommandText = str;
cmd.ExecuteNonQuery();
}

//提交事务
trans.Commit();//尤其是这
}
catch
{
success = false;
//回滚事务
trans.Rollback();
}
finally
{
Close();
}
return success;
}

一般情况下,执行单个查询的时候,不需要事务,因为一旦出错,操作也会失败。
在同时要执行多个查询,而且这些查询之间存在一定的依赖性的情况下,从考虑到数据合法性了完整性出发,应该使用事务。

总体上讲,事务的使用过程是这样的。

首先,事务是在一个数据库连接上进行了。

我们先创建一个SqlConnection,假设连接字符串为 connecti