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

两张表联查有错误了,来人帮我看看代码吧
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 + "'";
------解决方案--------------------
多表查询最好用join联查
cmd.CommandText = "select a.id,pid,x,y,recordno,name from road_local a inner join roadc1name_local b on b.id = a.id where name = '" + textBox2.Text + "'";

而为了安全起见,最好用参数代替textBox2.Text
cmd.CommandText = "select a.id,pid,x,y,recordno,name from road_local a inner join roadc1name_local b on b.id = a.id where name = @name";
SqlParameter sp=new SqlParameter("@name",textBox2.Text);
cmd.Parameters.Add(sp);