以下是查询数据库获取用户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 = 180
的 Users
列表是 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/