1 回答
TA贡献1757条经验 获得超8个赞
ExecuteScalar仅返回第一行的第一列。
如果您有很多行要读取,那么您需要调用ExecuteReader并使用返回的值进行循环,SqlDataReader.Read
直到返回 false。
循环时,您将查询结果存储在某种列表中,创建与读取器返回的信息相匹配的对象。
然后,这个列表可以很容易地用作某种用户界面对象(如 DataGridView 或类似对象)的数据源,或者用于将数据写入文件或其他存储。
// The model that describes the data returned by the query
public class TaskData
{
public string Name {get;set;}
public int Length {get;set;}
}
.....
// Where you store each record retrieved by the query
List<TaskData> results = new List<TaskData>();
using (SqlConnection con = new SqlConnection(_connectionString))
{
// Added the taskname to the query
string query = @"SELECT TaskName, SUM(TaskLength) as TaskLength
FROM myTable
WHERE EventStartTime
BETWEEN '2019/8/17' AND '2019/8/19'
GROUP BY TaskName ORDER BY TaskLength";
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
// Get a reader to loop over the results
using(SqlDataReader reader = cmd.ExecuteReader())
{
// Start reading data (until there are no more records to read)
while(reader.Read())
{
// From the current record build the TaskData info
TaskData data = new TaskData
{
Name = reader["TaskName"].ToString(),
Length = Convert.ToInt32(reader["TaskLength"]);
}
// Add this info the the collection of your results
results.Add(data);
}
}
}
}
现在,如果您想将结果存储到 CSV 文件中,代码很简单
File.WriteAllLines("yourFile.csv",
string.Join(Environment.NewLine,
results.Select(x => x.Name +","+x.Length))
- 1 回答
- 0 关注
- 133 浏览
添加回答
举报