插入表格时数据类型不匹配

时间:2014-07-26 22:54:35

标签: c# ms-access visual-studio-2012

我在将数据插入名为Order的Microsoft Access表时遇到了一些问题。我列出的方法是在我的数据访问层中创建的,并通过我的表示层中的Button Click事件调用。我得到的错误是:

  

标准表达式中的数据类型不匹配。

错误在cmd.ExecuteNonQuery()行突出显示:

数据访问层方法:

public static void processOrder(int employeeId, int tableId, DateTime orderDate, DateTime orderBegin, bool orderStatus)
{
   try
   {
      if (KaiConnection.State == ConnectionState.Closed)
         KaiConnection.Open();

      OleDbCommand cmd = new OleDbCommand(
         "INSERT INTO [Order] (EmployeeID, [TableID], OrderDate, OrderBegin, OrderStatus)" +
         " VALUES (?,?,?,?,?)", KaiConnection);
      //cmd.CommandText = sSQLCommand;
      cmd.Parameters.AddWithValue("?", employeeId);
      cmd.Parameters.AddWithValue("?", tableId);
      cmd.Parameters.AddWithValue("?", orderDate);
      cmd.Parameters.AddWithValue("?", orderBegin);
      cmd.Parameters.AddWithValue("?", orderStatus);

      // Execute the SQL command
      cmd.ExecuteNonQuery();
      KaiConnection.Close();
   }
   catch (Exception ex)
   {
      MessageBox.Show((ex.ToString()));
   }
}

表示层按钮点击事件:

private void btnProcessOrder_Click(object sender, EventArgs e)
{
   Order anOrder = new Order();
   anOrder.EmployeeId = empId;
   anOrder.TableId = int.Parse(txtTableID.Text);
   anOrder.OrderDate = DateTime.Today;
   anOrder.OrderBegin = DateTime.Now;
   anOrder.OrderStatus = true;
   anOrder.processOrder();
}

1 个答案:

答案 0 :(得分:1)

以下是使用OleDbParameter类对您的代码进行修改:

public static void processOrder(int employeeId, int tableId, DateTime orderDate, DateTime orderBegin, bool orderStatus)
{
    try
    {
        if (KaiConnection.State == ConnectionState.Closed)
            KaiConnection.Open();

        OleDbCommand cmd = new OleDbCommand("INSERT INTO [Order] (EmployeeID, [TableID], OrderDate, OrderBegin, OrderStatus)" +
                         " VALUES (@EmployeeID, @TableID, @OrderDate, @OrderBegin, @OrderStatus)", KaiConnection);

        OleDbParameter[] parameters = new OleDbParameter[5];
        parameters[0] = new OleDbParameter("@EmployeeID", OleDbType.Integer);
        parameters[1] = new OleDbParameter("@TableID", OleDbType.Integer);
        parameters[2] = new OleDbParameter("@OrderDate", OleDbType.Date);
        parameters[3] = new OleDbParameter("@OrderBegin", OleDbType.Date);
        parameters[4] = new OleDbParameter("@OrderStatus", OleDbType.Boolean);

        parameters[0].Value = employeeId;
        parameters[1].Value = tableId;
        parameters[2].Value = orderDate;
        parameters[3].Value = orderBegin;
        parameters[4].Value = orderStatus;

        for (int i = 0; i < 5; i++)
        {
            cmd.Parameters.Add(parameters[i]);
        }

        cmd.ExecuteNonQuery();
        cmd.Parameters.Clear();
        KaiConnection.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show((ex.ToString()));
    }
}