gpt4 book ai didi

c# - SQL查询结果到数组/列表

转载 作者:行者123 更新时间:2023-11-30 18:50:22 26 4
gpt4 key购买 nike

以下是查询数据库获取用户id列表的C#代码:

int id;
con = new SqlConnection(Properties.Settings.Default.ConnectionStr);
con.Open();
id = 180;
SqlCommand command = new SqlCommand("Select userid from UserProfile where grpid=@id", con);
command.Parameters.AddWithValue("@id", id);

using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader["userid"]));
}
}

con.Close();

Output: 5629

实际上,grpid = 180Users 列表是 5629、5684、5694

如何读取列表或数组中的结果?

最佳答案

简单地:

List<int> results = new List<int>();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
results.Add((int)reader["userid"]));
}
}
// use results

但是,您可能会发现像“Dapper”这样的工具可以节省您的时间

var results = con.Query<int>("Select userid from UserProfile where grpid=@id",
new { id }).AsList();

关于c# - SQL查询结果到数组/列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50211453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com