我正在尝试将两个SQL查询结果绑定到一个DataTable
,以便我可以将DataTable
设置为图表的数据源,但我不确定如何去做。我似乎无法将SQL查询结果添加到我需要的DataTable
中的特定列。
这是我的代码:
// retrieve connection from configuration settings
connection = new SqlConnection(RoleEnvironment.GetConfigurationSettingValue("DataConnectionString").ToString());
// Calling SQL query
SqlCommand commandGraph = new SqlCommand("SELECT AtmosphericPressure FROM Buoy3v3 WHERE time > '" + TextBox1_fromDate.Text + "' AND time < '" + TextBox2_toDate.Text + "';", connection);
commandGraph.CommandType = CommandType.Text;
SqlCommand commandGraph1month = new SqlCommand("SELECT AtmosphericPressure AS apMonth FROM Buoy3v3 WHERE time > (DATEADD(month, 1,'" + TextBox1_fromDate.Text + "')) AND time < (DATEADD(month, 1,'" + TextBox2_toDate.Text + "')) ;", connection);
commandGraph1month.CommandType = CommandType.Text;
//connection open
connection.Open();
DataTable dt = new DataTable();
dt.Columns.Add("AP");
dt.Columns.Add("AP1month");
using (SqlDataReader reader = commandGraph.ExecuteReader())
{
dt.Load(reader);
}
using (SqlDataReader reader1 = commandGraph1month.ExecuteReader())
{
dt.Load(reader1);
}
Chart1.DataSource = dt;
Chart1.Series["Series1"].YValueMembers = "AP";
Chart1.Series["Series1"].YValueMembers = "AP1month";
//connection close
connection.Close();
答案 0 :(得分:3)
仅使用一个查询。这样的事情可以奏效:
SELECT t1.AtmosphericPressure, t2.AtmosphericPressure
FROM Buoy3v3 t1
LEFT JOIN Buoy3v3 t2 ON t1.time = (DATEADD(month, 1,t2.time))
WHERE ...
这应该导致2条线并排运行 - 结果可能看起来像这样:
1 | ..xxxxx xxxxxxx
2 | x.... x x ......
3 | x . xx..
4 | ...
5 |_______________________
1 2 3 4 5
在您的代码中,您只有一列AtmosphericPressure
。如果你真的想使用2个查询,你可以让它们返回2列 -
SELECT AtmosphericPressure, null FROM Buoy3v3
SELECT null, AtmosphericPressure FROM Buoy3v3
这应该导致两行,但第二行将从第一次结束开始
此外,您的代码容易受到SQL注入攻击,请考虑使用参数化查询 - 例如commandGraph.Parameters.Add()