我需要为多个SQL服务器运行相同的SQL查询并获得结果 进入一个网格视图。
我得到的结果仅适用于一个数据库连接服务器, 如何为两台服务器重复网格视图? 谢谢大家,
网络配置:
<connectionStrings>
<add name="db1" connectionString="my connection string for server 1" />
<add name="db2" connectionString="my connection string for server 2" />
</connectionStrings>
asp.net:
<div>
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
</div>
C#:
string[] arr = new string[2] { "db1", "db2" };
arr[0] = ConfigurationManager.ConnectionStrings["db1"].ConnectionString;
arr[1] = ConfigurationManager.ConnectionStrings["db2"].ConnectionString;
for (int i = 0; i < arr.Length; i++)
{
SqlConnection con = new SqlConnection(arr[i]);
SqlCommand cmd = new SqlCommand("SELECT * from some sys.dm", con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
答案 0 :(得分:1)
您现在的逻辑将用您的第二个数据覆盖您的第一个数据源。您可能希望将两个数据源组合在一起并将它们绑定到GridView。
尝试这样的事情:
DataTable dtFinal = new DataTable();
foreach (string conString in arr)
{
DataTable dtTemp = new DataTable();
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT * from some sys.dm", con))
{
con.Open();
dtTemp.Load(cmd.ExecuteReader());
dtFinal.Merge(dtTemp);
}
}
}
GridView1.DataSource = dtFinal;
GridView1.DataBind();