日期:2014-05-18  浏览次数:20703 次

两张表联查有错误了,来人帮我看看代码
A 表中有字段id,x,y,pid,recordno,B表中有字段 name,id ,现在要根据b表中的name把a表中的所有字段查询并显示在datagridview上,如何实现?下面是我的代码:
 cmd.CommandText = "select a.id,a.pid,a.x,a.y,a.recordno,b.name from road_local a,roadc1name_local b where b.id = a.id AND b.name = " + textBox2.Text + ""; //textBox2中输入要查询的名字  
  DataSet dts = new DataSet();
  SqlDataAdapter dat = new SqlDataAdapter(cmd);
  dat.Fill(dts);
  //将查询结果显示在DataGridView上
  dataGridView2.DataSource = dts.Tables[0];

有错误,说是textbox2.text获取的值的列名有错

------解决方案--------------------
。。。。
b.name = '" + textBox2.Text + "'";
------解决方案--------------------
cmd.CommandText = "select a.id,a.pid,a.x,a.y,a.recordno,b.name from road_local a,roadc1name_local b where b.id = a.id AND b.name = " + textBox2.Text + ""; 
这句写错了 应该将那个文本框的值加上单引号。
正确写法是:

cmd.CommandText = "select a.id,a.pid,a.x,a.y,a.recordno,b.name from road_local a,roadc1name_local b where b.id = a.id AND b.name = '" + textBox2.Text + "'"; 

因为name 是string 类型的,需要带上’‘号