2013-01-31 42 views
2

如何從我的代碼隱藏文件執行SELECT查詢,然後遍歷它?執行從後面的代碼中選擇查詢

我想要做這樣的事情(只是一個簡單的例子僞):

// SQL Server 
var results = executeQuery("SELECT title, name FROM table"); 

foreach (var row in results) 
{ 
    string title = row.title; 
    string name = row.name; 
} 

我如何能做到這一點中的代碼?

+0

[這裏你去(http://msdn.microsoft.com/en-us/library/fksx3b4f(V = VS.80)的.aspx)! – Allov

+0

你知道SqlConnection,SqlCommand,SqlDataReader或SqlDataAdapter嗎? –

回答

6

事情是這樣的:

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(); 
    try 
    { 
     while (reader.Read()) 
     { 
      Console.WriteLine(String.Format("{0}, {1}", 
       reader["OrderID"], reader["CustomerID"])); 
     } 
    } 
} 

來源:http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx

connectionString的長短取決於數據庫產品和所使用的身份驗證機制(Windows驗證,用戶名/密碼等)。上面的示例假定您正在使用SQL Server。對於不同ConnectionStrings的完整列表,請http://www.connectionstrings.com/

+0

這不是查看我的情況。 – Scarl