【问题标题】:Finding out SQLParameters of a SQLCommand找出 SQLCommand 的 SQLParameters
【发布时间】:2011-10-11 07:56:53
【问题描述】:

在过去的某个时间,在我 VB6 的日子里,我记得能够创建一个 sql 命令对象(不一定与今天的 .NET 风格相同),并自动填充 sql 参数。

这让我可以做一些事情,比如只传递我肯定知道存在的参数,如果两个不同的客户端使用不同版本的数据库,我可以调用我的程序,知道我仍然会得到有意义的响应。

类似这样的:

Dim cmd as SqlCommand
Set cmd = New SqlCommand(Connection)
cmd.CommandText = "MagicStoredProcedure"
cmd.CommandType = CommandType.StoredProcedure
If cmd.Parameters.Count > 0 Then
    If cmd.Parameters(0).Name = "@FirstParameter" Then
        cmd.Parameters("@FirstParameter").Value = someValue
    End If
End If
Dim r as Recordset
Set r = cmd.ExecuteRecordset()

我记得这样做过,但我找不到任何自己的示例,并且尝试在 .NET 中执行此操作似乎根本不起作用。我看到的所有示例(并且我已经搜索了一段时间)手动添加参数。

任何指针?

【问题讨论】:

    标签: parameters sqlcommand


    【解决方案1】:

    我找到了 SQLCommandBuilder.DeriveParameters 过程,它完全符合我的要求。

    SQLCommandBuilder.DeriveParameters(cmd)
    If cmd.Parameters.Contains("@FirstParameter") Then
        cmd.Parameters("@FirstParameter").Value = someValue
    End If
    

    虽然不是我预期的那样。我希望它融入到 Command 对象或 Parameters 集合中。

    【讨论】:

    • 参数名称中不需要'@'前缀吗?
    【解决方案2】:

    我过去曾使用过一个模板解决方案来访问数据库,它使用映射到存储过程变量的类属性,并在需要时动态构建字符串。

    Look here for an explanation

    它看起来与您在使用 Visual Studio 时将存储过程和表从连接的数据库添加到项目时得到的非常相似。

    也许它可以为您指明正确的方向。

    【讨论】:

    • 感谢 Chris,但我看不到您的示例代码如何从服务器获取参数。它似乎依赖于您手动将它们添加到您的课程中。
    • 是的。我显然误解了,我很抱歉。
    猜你喜欢
    • 2011-02-16
    • 1970-01-01
    • 2013-03-08
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多