打印本文 打印本文 关闭窗口 关闭窗口
第三课 SqlCommand对象(翻译)
作者:武汉SEO闵涛  文章来源:敏韬网  点击数14792  更新时间:2007/11/14 13:12:47  文章录入:mintao  责任编辑:mintao
            // prepare command string
 
            string deleteString = @"
                 delete from Categories
                 where CategoryName = ''''Other''''";
 
 
            // 1. Instantiate a new command
 
            SqlCommand cmd = new SqlCommand();
 
 
           // 2. Set the CommandText property
 
            cmd.CommandText = deleteString;
 
 
           // 3. Set the Connection property
 
            cmd.Connection = conn;
 
 
            // 4. Call ExecuteNonQuery to send command
 
            cmd.ExecuteNonQuery();
         }
         finally
        
{
             // Close the connection
 
            if (conn != null)
             {
                 conn.Close();
             }
         }
     }
 
     /// <summary>
 
    /// use ExecuteScalar method
 
    /// </summary>
 
    /// <returns>number of records</returns>
 
    public int GetNumberOfRecords()
     {
         int count = -1;
 
         try
        
{
             // Open the connection
 
            conn.Open();
 
 
            // 1. Instantiate a new command
 
            SqlCommand cmd = new SqlCommand("select count(*) from Categories", conn);
 
 
            // 2. Call ExecuteNonQuery to send command
 
            count = (int)cmd.ExecuteScalar();
         }
         finally
        
{
            // Close the connection
 
            if (conn != null)
             {
                 conn.Close();
             }
         }
         return count;
     }
 }

In Listing 1, the SqlConnection object is instantiated in the SqlCommandDemo structure.  This is okay because the object itself will be cleaned up when the CLR garbage collector executes.  What is important is that we close the connection when we are done using it.  This program opens the connection in a try block and closes it in a finally block in each method.

在表1

 << 上一页  [11] [12] [13] [14] [15]  下一页

打印本文 打印本文 关闭窗口 关闭窗口