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 關注
- 178 瀏覽
添加回答
舉報