問題描述
我遇到了一個問題,我發(fā)現(xiàn)的所有文章或示例似乎都不關(guān)心它.
I've got a problem, and all articles or examples I found seem to not care about it.
我想在一個事務(wù)中做一些數(shù)據(jù)庫操作.我想要做的與大多??數(shù)示例非常相似:
I want to do some database actions in a transaction. What I want to do is very similar to most examples:
using (SqlConnection Conn = new SqlConnection(_ConnectionString))
{
try
{
Conn.Open();
SqlTransaction Trans = Conn.BeginTransaction();
using (SqlCommand Com = new SqlCommand(ComText, Conn))
{
/* DB work */
}
}
catch (Exception Ex)
{
Trans.Rollback();
return -1;
}
}
但問題在于 SqlTransaction Trans
是在 try
塊內(nèi)聲明的.所以它在 catch()
塊中是不可訪問的.大多數(shù)示例只是在 try
塊之前執(zhí)行 Conn.Open()
和 Conn.BeginTransaction()
,但我認(rèn)為這有點冒險,因為兩者都可以拋出多個異常.
But the problem is that the SqlTransaction Trans
is declared inside the try
block. So it is not accessable in the catch()
block. Most examples just do Conn.Open()
and Conn.BeginTransaction()
before the try
block, but I think that's a bit risky, since both can throw multiple exceptions.
我錯了,還是大多數(shù)人只是忽略了這種風(fēng)險?如果發(fā)生異常,能夠回滾的最佳解決方案是什么?
Am I wrong, or do most people just ignore this risk? What's the best solution to be able to rollback, if an exception happens?
推薦答案
using (var Conn = new SqlConnection(_ConnectionString))
{
SqlTransaction trans = null;
try
{
Conn.Open();
trans = Conn.BeginTransaction();
using (SqlCommand Com = new SqlCommand(ComText, Conn, trans))
{
/* DB work */
}
trans.Commit();
}
catch (Exception Ex)
{
if (trans != null) trans.Rollback();
return -1;
}
}
或者你可以更簡潔、更輕松地使用它:
or you could go even cleaner and easier and use this:
using (var Conn = new SqlConnection(_ConnectionString))
{
try
{
Conn.Open();
using (var ts = new System.Transactions.TransactionScope())
{
using (SqlCommand Com = new SqlCommand(ComText, Conn))
{
/* DB work */
}
ts.Complete();
}
}
catch (Exception Ex)
{
return -1;
}
}
這篇關(guān)于無法訪問 SqlTransaction 對象以在 catch 塊中回滾的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!