在Transaction.Commit()`之后,我的事务的connection属性被设置为null。我想知道连接对象发生了什么,它也被关闭了吗?
我想确保连接也被关闭。请建议一下。
因此,在调用方法时,我编写如下代码。
System.Data.SQLClient.SQLTransaction trans = null;
System.Data.SQLClient.SQLConnection oConn = null;
trans = oConn.GetIWSTransaction();
trans.commit();
and in GetIWSTransaction() as
Private System.Data.SQLClient.SQLTransaction m_oIWSTransaction =
null;
Private System.Data.SQLClient.SQLConnection m_oIWSConnection = null;
if(this.m_oIWSConnection.State = System.Data.ConnectionState.Closed)
this.m_oIWSConnection.Open();
this.m_oIWSTransaction = this.m_oIWSConnection.BeginTransaction();
return this.m_oIWSTransaction;
现在的问题是,调用方法中的trans.commit()
是否也终止了连接,还是将其设置为null。如果它只是将其设置为null,那么我们如何处理连接闭包?(除了使用块之外,还有其他选择)
发布于 2022-05-09 11:53:04
不,不需要。如果要关闭连接,建议的方法是将连接放在using
块中。例如。
using (DbConnection db = GetDbConnection())
{
db.Open();
}
当对象被释放时,连接将被关闭。
编辑:就像Charlie说的,理想情况下,事务也应该包含在一个using块中。
您甚至可以使用TransactionScope
#编辑:如果你正在学习,请遵循指南。例如这一个。
此外,这种低级别的starters (SqlClient和ADO.NET)不适合初学者使用。您应该考虑学习实体框架,或者可能是脱衣舞 (尽管后者已经适合更高级/更有经验的开发人员)。
回到你的密码。它的设计似乎没有很好的组织。试着遵循习惯性的设计,把事情保持在一起。
还有关于using
块。System.Data.SqlClient.SqlConnection
来源于DbConnection
,因此是IDisposable
。SqlTransaction
、DbTransaction
和IDisposable
也是如此。
因此,您的代码可能如下所示:
using System.Data.SqlClient;
using (SqlConnection connection = new SqlConnection(...connection string...))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
using (SqlTransaction transaction = connection.BeginTransaction("SampleTransaction"))
{
command.Transaction = transaction;
command.CommandText = ...your SQL...;
try
{
command.ExecuteNonQuery();
transaction.Commit();
}
catch (Exception ex)
{
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
}
}
}
}
https://stackoverflow.com/questions/72171385
复制相似问题