以下是一个示例,展示如何使用C#中的ExecuteReader方法执行查询:
using System; using System.Data.SqlClient; class Program { static void Main() { string connectionString = "Data Source=(local);Initial Catalog=YourDatabase;Integrated Security=True"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); string sql = "SELECT Id, Name, Age FROM Employees"; using (SqlCommand command = new SqlCommand(sql, connection)) { using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { int id = reader.GetInt32(0); string name = reader.GetString(1); int age = reader.GetInt32(2); Console.WriteLine($"Id: {id}, Name: {name}, Age: {age}"); } } } } } }
上面的示例中,我们首先创建一个SqlConnection对象,并提供数据库的连接字符串。然后,我们通过调用Open方法打开数据库连接。
接下来,我们创建一个SqlCommand对象,并传入要执行的SQL查询语句和连接对象。然后,我们使用ExecuteReader方法执行查询,并将结果返回给SqlDataReader对象。
在while循环内部,我们使用SqlDataReader的Read方法来逐行读取查询结果。然后,我们使用GetInt32和GetString等方法来获取每一行的列值,并将其打印到控制台上。
最后,我们使用using语句来确保在完成操作后正确地关闭数据库连接和相关资源。