Re: Place of BeginTransaction in code
- From: "Marina Levit [MVP]" <someone@xxxxxxxxxx>
- Date: Tue, 10 Oct 2006 10:59:08 -0400
Whether or not you set it to null is irrelevant. When you declare a
variable, it is already null. Setting it to null explitily doesn't change
the value of the variable.
In your exception, you are assuming you have a transaction. If the
connection could not be opened, no transaction would ever have been started.
"Mukesh" <cmukesh19@xxxxxxxxx> wrote in message
news:1160491482.452045.319590@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Hi,
In fact I tried declaring it on location 1 before posting. But as you
wrote, I was not setting it to anything. Thus I am getting the error
"Object reference not found...". But when I set it to null as Chris
suggested, it is working fine.
Thanks and Regards
Chakravarti Mukesh
Marina Levit [MVP] wrote:
Declare the transaction object outside the try/catch. Just don't set it
to
anything. Then, after you open the connection, inside the try block, set
the variable to the new transaction.
There is no law that says you have to declare the variable and set it to
something in the same line. You can declare everything at the top of your
method, and then use it later. In fact, that is my personal preference,
just to see all the variables involved in my method, so I don't have to
track them down throughout the method.
"Mukesh" <cmukesh19@xxxxxxxxx> wrote in message
news:1160485739.992551.62380@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Hi all,
Consider this code
SqlConnection oConn = new
SqlConnection(AccountsConnectionString);
SqlCommand cmdInsert = new SqlCommand("UpdateQuery");
//Location 1:
//SqlTransaction sqlTran = oConn.BeginTransaction();
try
{
oConn.Open();
//Location 2:
//SqlTransaction sqlTran = oConn.BeginTransaction();
cmdInsert.ExecuteNonQuery();
sqlTran.Commit();
}
catch (Exception ex)
{
//Location 3:
sqlTran.Rollback();
}
finally
{
oConn.Close();
}
I have to start a transaction and commit or rollback depending upon the
condition of success of command execution. The problem is if I write
code to Begin Transaction at location 1 it won't work as connection is
still closed. If I write the same at location 2, I won't be able to
rollback transaction at location 3 as sqlTran object is out of
referance. What should I do? I am using framework 2.0.
Thanks and Regards
Chakravarti Mukesh
.
- Follow-Ups:
- Re: Place of BeginTransaction in code
- From: Mark Wilden
- Re: Place of BeginTransaction in code
- References:
- Place of BeginTransaction in code
- From: Mukesh
- Re: Place of BeginTransaction in code
- From: Marina Levit [MVP]
- Re: Place of BeginTransaction in code
- From: Mukesh
- Place of BeginTransaction in code
- Prev by Date: Re: Default property
- Next by Date: Re: Using Generics with System.DirectoryServices
- Previous by thread: Re: Place of BeginTransaction in code
- Next by thread: Re: Place of BeginTransaction in code
- Index(es):
Relevant Pages
|