Recently, I was asked a question about how to perform joint queries on the tables in the two databases.
Then I implemented it in the most stupid way. Hope you can see a good solution, just use a connection string. It is best to give a detailed tutorial.
First, there are two such databases, each with two tables.
The data in the table is also very simple, that is, the student table and the professional table are associated with the professional number.
Next, bind data to the Winfrom DataGridView to display the student ID, name, age, and major. The effect is as follows:
Because I have used linq to dataset for data operations, the. net version of the project is later than 3.5.
The following code binds data:
1: using System;
2: using System. Collections. Generic;
3: using System. ComponentModel;
4: using System. Data;
5: using System. Drawing;
6: using System. Text;
7: using System. Windows. Forms;
8: using System. Data. SqlClient;
9: using System. Linq;
10: namespace LinkTwoData
11 :{
12: public partial class Form1: Form
13 :{
14: public Form1 ()
15 :{
16: InitializeComponent ();
17 :}
18: string strcon1 = @ "Data Source = FENG-PC \ SQLEXPRESS; Initial Catalog = test1; User ID = sa; PassWord = sa2008 ";
19: string strcon2 = @ "Data Source = FENG-PC \ SQLEXPRESS; Initial Catalog = test2; User ID = sa; PassWord = sa2008 ";
20: private void Form1_Load (object sender, EventArgs e)
21 :{
22: SqlDataAdapter sda1 = new SqlDataAdapter ("select * from stu1", strcon1 );
23: SqlDataAdapter sda2 = new SqlDataAdapter ("select * from stu1", strcon2 );
24: DataSet ds = new DataSet ();
25: sda1.Fill (ds, "stu1 ");
26: sda2.Fill (ds, "stu2 ");
27:
28: var query = from stu in ds. Tables ["stu1"]. AsEnumerable ()
29: from SC in ds. Tables ["stu2"]. AsEnumerable ()
30: where stu. Field <int> ("SC") = SC. Field <int> ("SC ")
31: select new
32 :{
33: sno = stu. Field <int> ("sno", DataRowVersion. Original ),
34: sname = stu. Field <string> ("sname", DataRowVersion. Original ),
35: sage = stu. Field <int> ("sage", DataRowVersion. Original ),
36: scname = SC. Field <string> ("scname", DataRowVersion. Original)
37 :};
38:
39: DataTable dt = new DataTable ();
40: dt. Columns. Add ("sno", typeof (int ));
41: dt. Columns. Add ("sname", typeof (string ));
42: dt. Columns. Add ("sage", typeof (string ));
43: dt. Columns. Add ("scname", typeof (string ));
44: foreach (var item in query)
45 :{
46: DataRow newRow = dt. NewRow ();
47: newRow ["sno"] = item. sno;
48: newRow ["sname"] = item. sname;
49: newRow ["sage"] = item. sage;
50: newRow ["scname"] = item. scname;
51: dt. Rows. Add (newRow );
52 :}
53: Maid = dt. DefaultView;
54 :}
55 :}
56 :}
Let me know if you want to implement this function better.
From Han Xiaofeng