【问题标题】:Creating a SQLCommand for use in a SQLDataAdapter创建用于 SQLDataAdapter 的 SQLCommand
【发布时间】:2009-03-04 20:06:37
【问题描述】:

我正在尝试使用SQLDataAdapter 从表中删除数据,为此我需要给它一个DeleteCommand

我用来删除一行的 SQL 是:

DELETE FROM table WHERE ID = x

因此问题是:如何指定DataAdapter 用什么替换x?生成 DataAdapter 的 SQL 与被告知要更新的数据表(外连接)略有不同(无连接)。

我该怎么做?

【问题讨论】:

    标签: c# sql-server ado.net


    【解决方案1】:

    这里你可以传递参数给删除命令:

    // 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;
    

    代码取自MSDN

    【讨论】:

    • 我需要用这个检查 SQL 注入吗?
    • 不,你没有,你将输入作为参数传递。
    【解决方案2】:

    使用 SourceColumn 和 SourceVersion SqlParameter 属性:

            var deleteCommand = connection.CreateCommand();
            deleteCommand = "DELETE FROM table WHERE ID = @ID";
            var param = new SqlParameter("ID");
            param.SourceColumn = "the Select Column";
            param.SourceVersion = DataRowVersion.Original;
            deleteCommand.Parameters.Add (param);
    

    【讨论】:

    • 你能解释一下 SourceVersion 是什么吗?
    • SourceVersion 表示将使用哪个值,Original 是您通过 select 查询获得的原始值,Current 是该字段的当前值,就像您修改它一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多