【问题标题】:SqlDataAdapter.DeleteCommand() works with AddWithValue() but not with Add() - Why?SqlDataAdapter.DeleteCommand() 适用于 AddWithValue() 但不适用于 Add() - 为什么?
【发布时间】:2012-10-16 02:24:10
【问题描述】:

Microsoft's own documentation提供了一个删除记录的例子,如下:

// Create the DeleteCommand.
command = new SqlCommand(
    "DELETE FROM Customers WHERE CustomerID = @CustomerID", connection);

// Add the parameters for the DeleteCommand.
parameter = command.Parameters.Add(
    "@CustomerID", SqlDbType.NChar, 5, "CustomerID");
parameter.SourceVersion = DataRowVersion.Original;

adapter.DeleteCommand = command;

但在我的系统上它不起作用(抱怨缺少@CustomerID)。相反,如果我更换

command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");

上面有

command.Parameters.AddWithValue("@CustomerID", 5);

It works.

为什么?

【问题讨论】:

    标签: c# sql-server sqldataadapter


    【解决方案1】:

    在这一行:

    command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
    

    在这个重载中,5 指的是参数的长度,而不是值。如果要添加值,则必须添加以下内容:

    command.Parameters["@CustomerID"].Value = "5";
    

    【讨论】:

      猜你喜欢
      • 2017-05-08
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 2020-07-28
      • 2017-08-20
      • 2012-12-23
      • 2013-10-08
      相关资源
      最近更新 更多