string sqlStatement = "SELECT Orders.[ID], Orders.[Checkintime], Orders.[RoomPrice], Orders.[OrderNo], Particulars.FirstName, Particulars.LastName FROM Orders, where Checkintime between '" + dateOnly + "' and '" + endDateOnly + "', Particulars;";
我尝试使用此语句从我的数据库中选择信息,但此语句包含来自FROM子句的语法错误
答案 0 :(得分:2)
我认为这两个表(订单和详细信息)由一些充当外键的字段连接在一起。所以你应该在Particulars表中有一个OrderID字段,它链接每个特定的'各自的订单。
如果是这种情况,那么您的查询应该是这样的
string sqlStatement = @"SELECT Orders.[ID], Orders.[Checkintime],
Orders.[RoomPrice], Orders.[OrderNo],
Particulars.FirstName, Particulars.LastName
FROM Orders INNER JOIN Particulars
ON Orders.[ID] = Particulars.[OrderID]
where Checkintime between '" + dateOnly +
"' and '" + endDateOnly + "'";
然而,这种使用字符串连接的方法容易出现其他类型的错误,如解析问题和Sql注入,更好地使用参数化查询
string sqlStatement = @"SELECT Orders.[ID], Orders.[Checkintime],
Orders.[RoomPrice], Orders.[OrderNo],
Particulars.FirstName, Particulars.LastName
FROM Orders INNER JOIN Particulars
ON Orders.[ID] = Particulars.[OrderID]
where Checkintime between @init AND @end";
using(SqlConnection cnn = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand(sqlStatement, cnn))
{
cnn.Open();
cmd.Parameters.Add("@init", SqlDbType.DateTime).Value = dateOnly;
cmd.Parameters.Add("@end", SqlDbType.DateTime).Value = endDateOnly;
.... remainder of your code that reads back your data.....
}
请注意,提供给Parameter.Value的值应该是DateTime变量而不是字符串....
答案 1 :(得分:1)
删除,
Orders, where
, Particulars;
也没有明确表示您应该使用联接... FROM Orders join Particulars ON Orders.ID = Particulars.ID
或ID列名称
根据您的文化,DateTime在作为字符串值'04/08/2015 21:52:39'
传递时可能会导致问题。例如在某些文化中,日和月交换。您可以dateOnly.ToString("yyyy-MM-dd")
或更好地使用参数并传递DateTime对象以避免额外的注入攻击
答案 2 :(得分:0)
您需要加入查询:
string sqlStatement = "SELECT Orders.[ID], Orders.[Checkintime], Orders.[RoomPrice], Orders.[OrderNo], Particulars.FirstName, Particulars.LastName FROM Orders inner join Particulars on Orders.CommonField=Particulars.CommonField
where Checkintime between '" + dateOnly + "' and '" + endDateOnly + "'";