关于查询问题,数据库中可以查询,C#中有错
先来代码:SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=Train;Integrated Security=True");
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "select a.TrainId as 车次,a.StationName as 起始站,b.StationName as 终点站," +
"convert(varchar,a.ArriveTime,108) as 到站时间,convert(varchar,b.ArriveTime-a.LeaveTime,108) as 运行时间," +
"b.Distance-a.Distance as 距离km,b.Date as 日期" +
"from Trains a inner join Trains b" +
"on a.TrainId=b.TrainId and a.StationName='" + start + "' and b.StationName='" + end + "'";
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
GridView1.Visible = true;
GridView1.DataSource = sdr;
GridView1.DataBind();
con.Close();
在数据库中查询是正确的,但是在.net中就老实提示“trians”附近有错.为啥呢?
------解决方案--------------------方法1:每个引后(前)加加个空格。问题所以见下面
红字
"from Trains a inner join Trains
b" +
"b.Distance-a.Distance as 距离km,b.Date as 日期" +
方法2:多行的Sql语句使用@开头就可以换行面不需要在中间加 双引号了。
@"。。。。。。
from Trains a inner join Trains b
b.Distance-a.Distance as 距离km,b.Date as 日期
。。。。。"
------解决方案--------------------"from Trains a inner join Trains b "
拼接sql字符串的时候注意空格
------解决方案--------------------应该是空格的原因
------解决方案--------------------遇到这种情况向输出界面显示一下cmd.CommandText就能看到清楚的程序形成SQL语句了。检查SQL语法就一目了然了。