我正在尝试用C#写一个SQL查询到Access。 该查询在Access软件中工作正常,但是当我尝试通过带参数的C#运行它时,它会抛出参数丢失的异常。它就像它忽略了我给出的参数。 这是我的方法:
public DataTable GetRoomStatusByDate(Room RoomItem, TimeRange TimeItem, WeekDay DayItem, DateTime DateItem)
{
string cmdStr = "SELECT Subject, AdditionOrCancellation, Description " +
"FROM (SELECT * " +
"FROM TimeTables TT1 LEFT OUTER JOIN SpecialEvents SE1 " +
"ON TT1.RoomNumber = SE1.RoomNumber AND TT1.StructureNumber = SE1.StructureNumber AND " +
"TT1.DayNumber = SE1.DayNumber AND TT1.HourNumber = SE1.HourNumber " +
"UNION " +
"SELECT * " +
"FROM TimeTables TT2 RIGHT OUTER JOIN SpecialEvents SE2 " +
"ON TT2.RoomNumber = SE2.RoomNumber AND TT2.StructureNumber = SE2.StructureNumber " +
"AND TT2.DayNumber = SE2.DayNumber AND TT2.HourNumber = SE2.HourNumber) " +
"WHERE (TT1.RoomNumber = @TTRoomNumber OR SE1.RoomNumber = @SERoomNumber) AND (TT1.StructureNumber = @TTStructureNumber OR SE1.StructureNumber = @SEStructureNumber) " +
"AND(TT1.HourNumber = @TTHourNumber OR SE1.HourNumber = @SEHourNumber) AND (TT1.DayNumber = @TTDayNumber OR SE1.DayNumber = @@SEDayNumber) " +
"AND (SE1.EventDate = @SEEventDate OR SE1.EventDate IS NULL)";
DataSet ds = new DataSet();
using (OleDbCommand command = new OleDbCommand(cmdStr))
{
command.Parameters.AddWithValue("@TTRoomNumber", RoomItem.Number);
command.Parameters.AddWithValue("@SERoomNumber", RoomItem.Number);
command.Parameters.AddWithValue("@TTStructureNumber", RoomItem.Structure);
command.Parameters.AddWithValue("@SEStructureNumber", RoomItem.Structure);
command.Parameters.AddWithValue("@TTDayNumber", TimeItem.Number);
command.Parameters.AddWithValue("@SEDayNumber", TimeItem.Number);
command.Parameters.AddWithValue("@TTDayNumber", DayItem.Number);
command.Parameters.AddWithValue("@SEDayNumber", DayItem.Number);
command.Parameters.AddWithValue("@SEEventDate", DateItem);
ds = GetMultipleQuery(command);
}
DataTable dt = new DataTable();
try
{
dt = ds.Tables[0];
}
catch
{ }
return dt;
}
我还想提一下我使用OLEDB并且我的连接非常好,因为我有很多查询和参数的方法,它们一切正常,没有任何问题。 这是我唯一一个查询不起作用的方法。
答案 0 :(得分:2)
OleDb使用位置参数,而不是命名参数。在SQL中用?
替换参数名称。您可以在AddWithValue
中保持参数名称不变,因为它会被忽略。
...
"WHERE (TT1.RoomNumber = ? OR SE1.RoomNumber = ?) AND (TT1.StructureNumber = ? OR SE1.StructureNumber = ?) " +
"AND(TT1.HourNumber = ? OR SE1.HourNumber = ?) AND (TT1.DayNumber = ? OR SE1.DayNumber = ?) " +
"AND (SE1.EventDate = ? OR SE1.EventDate IS NULL)";
确保以与SQL文本中出现的顺序相同的顺序添加参数。
传递给AddWithValue
的值也必须具有正确的类型。数字或日期字符串不会自动转换为相应的数字或日期时间类型。