首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

两张表联查有异常了,来人帮小弟我看看代码吧

2012-06-13 
两张表联查有错误了,来人帮我看看代码吧A 表中有字段id,x,y,pid,recordno,B表中有字段 name,id ,现在要根

两张表联查有错误了,来人帮我看看代码吧
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);

热点排行