在C#中,使用SqlCommand對象的ExecuteReader()方法執行查詢。具體步驟如下:
示例代碼如下:
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT * FROM MyTable";
SqlCommand command = new SqlCommand(query, connection);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// 讀取查詢結果
Console.WriteLine(reader["ColumnName"]);
}
}
}
}
}
請注意,上述代碼僅為示例,實際應用中需要根據情況做適當的異常處理和資源釋放。