最近被问道了一个问题,就是如何对两个数据库里面的表进行联合查询。
后来我就用了最笨的方法实现了。希望看到的朋友能给个好的解决方法,只用一个连接字符串。最好是给个详细的教程。
表里面的数据也很简单,就是学生表和专业表,用专业号关联。
下面就在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