// 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] 下一页 |