人生是一场不能存盘的RPG,我只能尽量多搞几个Screenshot

August 10, 2006

SqlConnection 和 SqlTrasaction应该先dispose哪一个?

Filed under: SQL&DB Accessing

我的代码

string connstr= @\"Data Source=.\sql2k5;Initial Catalog=SQLStudy; Integrated Security=SSPI\";
SqlConnection conn = null;
SqlTransaction trans = null;
try
{
        conn = new SqlConnection(connstr);
        conn.Open();
        trans = conn.BeginTransaction();
        string sql = \"Insert into Student values(100, 'ak47')\";
        // Must assign both transaction object and connection
        // to Command object for a pending local transaction
        //new SqlCommand(sql, trans.Connection);会报错!
        SqlCommand command = new SqlCommand(sql, trans.Connection, trans);
        command.ExecuteNonQuery();
        trans.Commit();
}
catch (Exception exp)
{
        Console.WriteLine(exp.Message);
        if(trans != null)
        {
                trans.Rollback();
        }
}
finally
{
        if(conn != null)
        {
                conn.Close();
        }
        if(trans != null)
        {
                trans.Dispose();
        }
}

MSDN

using (SqlConnection conn = new SqlConnection(dbConString))
{
   conn.Open();
   using (SqlTransaction trans = conn.BeginTransaction())
   {
      try
      {
         ...
              trans.Commit();
      }
      catch
      {
         trans.Rollback();
      }
   }
}
	

Comments »

The URI to TrackBack this entry is: http://recordsome.blogsome.com/2006/08/10/p142/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.






















Get free blog up and running in minutes with Blogsome
Theme designed by Hadley Wickham