2011-03-15 108 views
2

有什麼教程可以在SQL Server 2008中執行此操作嗎? 你有沒有例子?使用ADO.NET從SQL Server獲取數據

是否有可能執行存儲過程並在C#中獲取結果?

+0

http://msdn.microsoft.com/en-us/sqlserver/ff681103 – 2011-03-15 02:08:30

+0

我會首先推薦理解概念。 ADO.NET代碼與SQL Server 2005/2008的工作方式沒有什麼區別。它們都在於System.Data.SQLClient命名空間提供的對象以及它們如何相關/不同以及這些對象具有哪些方法。 – sajoshi 2011-03-15 03:00:35

回答

8

一個良好的開端是SqlDataReader類:

private static void ReadOrderData(string connectionString) 
{ 
    string queryString = 
     "SELECT OrderID, CustomerID FROM dbo.Orders;"; 

    using (SqlConnection connection = 
       new SqlConnection(connectionString)) 
    { 
     SqlCommand command = 
      new SqlCommand(queryString, connection); 
     connection.Open(); 

     SqlDataReader reader = command.ExecuteReader(); 

     // Call Read before accessing data. 
     while (reader.Read()) 
     { 
      Console.WriteLine(String.Format("{0}, {1}", 
       reader[0], reader[1])); 
     } 

     // Call Close when done reading. 
     reader.Close(); 
    } 
} 

更具體地說:Using parameters with a SqlCommand and a Stored Procedure

static void GetSalesByCategory(string connectionString, 
    string categoryName) 
{ 
    using (SqlConnection connection = new SqlConnection(connectionString)) 
    { 
     // Create the command and set its properties. 
     SqlCommand command = new SqlCommand(); 
     command.Connection = connection; 
     command.CommandText = "SalesByCategory"; 
     command.CommandType = CommandType.StoredProcedure; 

     // Add the input parameter and set its properties. 
     SqlParameter parameter = new SqlParameter(); 
     parameter.ParameterName = "@CategoryName"; 
     parameter.SqlDbType = SqlDbType.NVarChar; 
     parameter.Direction = ParameterDirection.Input; 
     parameter.Value = categoryName; 

     // Add the parameter to the Parameters collection. 
     command.Parameters.Add(parameter); 

     // Open the connection and execute the reader. 
     connection.Open(); 
     SqlDataReader reader = command.ExecuteReader(); 

     if (reader.HasRows) 
     { 
      while (reader.Read()) 
      { 
       Console.WriteLine("{0}: {1:C}", reader[0], reader[1]); 
      } 
     } 
     else 
     { 
      Console.WriteLine("No rows found."); 
     } 
     reader.Close(); 
    } 
} 
+0

只要一件事,你可以在using子句中使用SqlDataReader以獲得更好的方式。 (reader.Read()) Console.WriteLine(「{0}:{1:C}」,reader [0],reader [1]);如果(reader.HasRows) { while(reader.Read()) } } else { Console.WriteLine(「No rows found。」); } – 2011-03-15 03:46:55

+1

** @ ydobonmai **在這裏領先一步...但如果你想挑選一個,SqlCommand也是一次性的。當我們處理它時,可能還需要添加異常處理。嘿,讓我們爲他寫一個Asker的代碼吧。 – 2011-03-15 03:53:22

相關問題