c#中executereader执行查询示例分享

c#
516
2023/8/9 13:45:12
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

以下是一个示例,展示如何使用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语句来确保在完成操作后正确地关闭数据库连接和相关资源。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c#中Request.QueryString接受多个参数问题怎么解决