最近被問道了一個問題,就是如何對兩個數據庫里面的表進行聯合查詢。
后來我就用了最笨的方法實現了。希望看到的朋友能給個好的解決方法,只用一個連接字符串。最好是給個詳細的教程。
表里面的數據也很簡單,就是學生表和專業表,用專業號關聯。
下面就在Winfrom的DataGridView上綁定數據,顯示學生的編號、姓名、年齡和專業。效果如下:
由於對數據的操作我用到了linq to dataset 所以項目的.net 版本為3.5以上。
下面就是綁定數據的代碼:
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: dataGridView1.DataSource = dt.DefaultView;
54: }
55: }
56: }
希望有更好實現這個功能的前輩,告訴我一下。
作者QQ:29992379