SELECT COUNT查询错误

时间:2016-03-18 14:01:03

标签: c# parameters oledbcommand

我有这个代码,我正在尝试在accessdatabase datatable [Holiday]中计算具有特定payrollno的行。

string CountHolidayQuery = "SELECT COUNT FROM [Holiday] WHERE PayrollNo = @PayrollNo";
var CountHoliday = new OleDbCommand(CountHolidayQuery, conn);
CountHoliday.Parameters.AddWithValue("@PayrollNo", OleDbType.Integer).Value = GotPayroll;
int TotalHolidays = Convert.ToInt32(CountHoliday.ExecuteNonQuery());

我收到此错误,但我认为我添加了参数?

  

抛出异常:System.Data.dll中的'System.Data.OleDb.OleDbException'   附加信息:没有给出一个或多个必需参数的值。

2 个答案:

答案 0 :(得分:3)

COUNT的正确语法是

string CountHolidayQuery = @"SELECT COUNT(*) 
         FROM [Holiday] WHERE PayrollNo = @PayrollNo";
var CountHoliday = new OleDbCommand(CountHolidayQuery, conn);
CountHoliday.Parameters.Add("@PayrollNo", OleDbType.Integer).Value = GotPayroll;
int TotalHolidays = Convert.ToInt32(CountHoliday.ExecuteNonQuery());

另请注意,我已将调用更改为AddWithValue,并为传递的参数添加了正确的Add。考虑到AddWithValue应该引起很多关注,因为it is know as a source for subtle bugs

答案 1 :(得分:3)

尝试

string CountHolidayQuery = 
   @"SELECT COUNT(*) 
       FROM [Holiday] 
      WHERE PayrollNo = @PayrollNo";

int TotalHolidays;

using (var CountHoliday = new OleDbCommand(CountHolidayQuery, conn)) {
  CountHoliday.Parameters.Add("@PayrollNo", OleDbType.Integer).Value = GotPayroll;
  TotalHolidays = Convert.ToInt32(CountHoliday.ExecuteNonQuery());
}