对catch子句中已存在的SqlTransaction RollBack实现错误处理的最佳方式是什么?我的代码大致是这样的:如何在RollBack上捕获异常
using (SqlConnection objSqlConn = new SqlConnection(connStr)) {
objSqlConn.Open();
using (SqlTransaction objSqlTrans = objSqlConn.BeginTransaction()) {
try {
// code
// more code
// and more code
}
catch (Exception ex) {
// What happens if RollBack() has an exception?
objSqlTrans.Rollback();
throw ex;
}
}
}
我相信我的应用程序必须在try块,而这又被夹在catch块,然后回滚试图在一个例外。但是,我看到的错误说了一些关于SqlTransaction.ZombieCheck()的问题,这让我怀疑RollBack()本身是否也抛出了异常。那么,我需要在RollBack()中实现某种类型的错误处理吗?我该怎么做,并设法保留将执行放入catch块的异常呢?
编辑 - 我的所有代码:
using (SqlConnection objSqlConn = new SqlConnection(connStr)) {
objSqlConn.Open();
// Begin Transaction
using (SqlTransaction objSqlTrans = objSqlConn.BeginTransaction()) {
try {
// Create file in db (which in turn creates it on disk according to where the
// ...FileStream points)
SqlCommand objSqlCmd = new SqlCommand("usp_FileAdd", objSqlConn, objSqlTrans);
objSqlCmd.CommandType = CommandType.StoredProcedure;
// Sql parameter - report name
SqlParameter objSqlParam1 = new SqlParameter("@ObjectID", SqlDbType.Int);
objSqlParam1.Value = objID;
// Sql out parameter - returns the file path
SqlParameter objSqlParamOutput = new SqlParameter("@filepath", SqlDbType.VarChar, -1);
objSqlParamOutput.Direction = ParameterDirection.Output;
// Add Sql parameters to command obj
objSqlCmd.Parameters.Add(objSqlParam1);
objSqlCmd.Parameters.Add(objSqlParamOutput);
// Execute command object
objSqlCmd.ExecuteNonQuery();
// Path to the FileStream
string path = objSqlCmd.Parameters["@filepath"].Value.ToString();
// Reset command object to get FileStream
objSqlCmd = new SqlCommand(
"SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()",
objSqlConn,
objSqlTrans);
// Execute command object
Object obj = objSqlCmd.ExecuteScalar();
if (obj != DBNull.Value) {
// Byte array representing the FileStream
byte[] fsBytes = (byte[])obj;
SqlFileStream sqlFS = new SqlFileStream(path, fsBytes, FileAccess.Write);
using (FileStream fs = fi.OpenRead()) {
//byte[] b = new byte[1024];
byte[] b = new byte[4096];
int read;
fs.Seek(0, SeekOrigin.Begin);
while ((read = fs.Read(b, 0, b.Length)) > 0) {
sqlFS.Write(b, 0, read);
}
}
sqlFS.Close();
}
// Commit the transaction
objSqlTrans.Commit();
}
catch (Exception ex) {
objSqlTrans.Rollback();
throw ex;
}
}
}
我想你可能已经钉住了它。我在SO上发现了另一个关于使用SqlTransaction块处理的问题,并且我注意到他们的例子中他们也没有使用Rollback。我不认为我的问题是该问题的重复。 http://stackoverflow.com/questions/1127830/why-use-a-using-statement-with-a-sqltransaction – Jagd 2010-04-05 17:18:49
确定回滚将尝试没有显式,但它会保留内部异常,而不是抛出一个异常没有更可能的原因? – Maslow 2014-10-24 14:57:52
@Maslow使用语句不会影响异常中的内容。所以如果有一个由SqlCommand.ExecuteScalar提供的内部异常,它将被保留。 – 2014-10-24 17:43:19