如何使用SqlDataReader连接到asp.net中的多个数据库?
假设我有两个数据库,例如“Product”和“people”。产品数据库有两个表,比如table1和表2,而人们有两个表,让我们再说一次table1和table2。 我想从Product.table1获取一些信息,并从people.table2获取一些信息。
我尝试使用以下代码,但不幸的是它不起作用:
SqlConnection con1 = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Product.mdf;Integrated Security=True");
SqlConnection con2 = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\People.mdf;Integrated Security=True");
SqlCommand cmd1 = new SqlCommand("select prod_name, prod_price from product_tbl", con1);
SqlCommand cmd2 = new SqlCommand("select std_name from student_tbl", con2);
con1.Open();
con2.Open();
SqlDataReader dr1 = cmd1.ExecuteReader();
SqlDataReader dr2 = cmd2.ExecuteReader();
// GridView1.DataSource = How to do it??
GridView1.DataBind();
答案 0 :(得分:0)
您可以按照以下方式执行此操作:
从dataset1
从dataset2中的人员DB中检索结果
使用DataSet.Merge方法合并单个数据集中的两个数据集,例如dsProductPeople
将dsProductPeople绑定到网格
OR 您可以使用以下示例:
// Assumes that customerConnection is a valid SqlConnection object.
// Assumes that orderConnection is a valid OleDbConnection object.
SqlDataAdapter custAdapter = new SqlDataAdapter(
"SELECT * FROM dbo.Customers", customerConnection);
OleDbDataAdapter ordAdapter = new OleDbDataAdapter(
"SELECT * FROM Orders", orderConnection);
DataSet customerOrders = new DataSet();
custAdapter.Fill(customerOrders, "Customers");
ordAdapter.Fill(customerOrders, "Orders");
DataRelation relation = customerOrders.Relations.Add("CustOrders",
customerOrders.Tables["Customers"].Columns["CustomerID"],
customerOrders.Tables["Orders"].Columns["CustomerID"]);
foreach (DataRow pRow in customerOrders.Tables["Customers"].Rows)
{
Console.WriteLine(pRow["CustomerID"]);
foreach (DataRow cRow in pRow.GetChildRows(relation))
Console.WriteLine("\t" + cRow["OrderID"]);
}