以下是用于查询数据库以获取用户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();
输出:5629
实际上,具有
Users
的grpid = 180
列表是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/