C# GetAllCustomers()方法
我們在使用存儲過程時,經(jīng)常會SELECT一條或多條記錄。 你可以采用兩種方法來創(chuàng)建這樣的存儲過程。
首先我們創(chuàng)建一個名為C# GetAllCustomers()方法,代碼如下:
- public static void GetAllCustomers()
- {
- SqlConnection cnn = new SqlConnection
- ("context connection=true");
- cnn.Open();
- SqlCommand cmd = new SqlCommand();
- cmd.Connection = cnn;
- cmd.CommandText = "select * from customers";
- SqlDataReader reader = cmd.ExecuteReader();
- SqlContext.Pipe.Send(reader);
- reader.Close();
- cnn.Close();
- }
這個C# GetAllCustomers()方法用了一個[SqlProcedure]屬性來修飾。 在方法內創(chuàng)建一個SqlConnection和一個SqlCommand對象。然后使用ExecuteReader()方法來執(zhí)行SELECT語句。接下來用Send()方法將取得的SqlDataReader數(shù)據(jù)發(fā)送到客戶端。***就是關閉SqlDataReader和SqlConnection。 在這種方法中,是我們自己創(chuàng)建的SqlDataReader。其實,我們也可以把這個任務交給SqlContext類去完成,代碼如下:
- public static void GetCustomerByID
- (SqlString CustomerID)
- {
- SqlConnection cnn = new SqlConnection
- ("context connection=true");
- cnn.Open();
- SqlCommand cmd = new SqlCommand();
- cmd.Connection = cnn;
- cmd.CommandText = "select * from customers
- where customerid=@p1";
- SqlParameter p1 = new SqlParameter("@p1", CustomerID);
- cmd.Parameters.Add(p1);
- SqlContext.Pipe.ExecuteAndSend(cmd);
- cnn.Close();
- }
GetCustomerByID()方法需要一個參數(shù) – CustomerID,它將從Customers表中返回某個customer的記錄。這個方法內的代碼,除了ExecuteAndSend()方法外,你應該都已經(jīng)比較熟悉了。 ExecuteAndSend()方法接收一個SqlCommand對象作為參數(shù),執(zhí)行它就會返回數(shù)據(jù)集給客戶端。以上介紹C# GetAllCustomers()方法
【編輯推薦】