在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"]);
}
}
}
}
}
请注意,上述代码仅为示例,实际应用中需要根据情况做适当的异常处理和资源释放。