从VB.NET调用存储过程时出现问题

时间:2011-05-06 18:56:49

标签: asp.net database vb.net visual-studio

我是VB的新手,我不知道为什么这不起作用,基本上我试图从我的网络代码运行存储过程。 sp在SQL中运行得很好,我已经多次尝试过了,所以我确信这不是问题所在。我不想退回任何结果,我只想看到一个" ok"语句是否运行,如果没有,则显示错误消息。我用于标签的代码(警告和确认)从早期在同一页面上重用,验证(valUpload)也是如此。我确信解决方案很简单......

Protected Sub RunValidation_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles RunValidation.Click
    Try
        Dim bl As New BL.ORG
        Dim db As Database = DatabaseFactory.CreateDatabase("MyConnection")
        Dim dbCommand As DbCommand

        db = DatabaseFactory.CreateDatabase("MyConnection")
        dbCommand = db.GetStoredProcCommand("Company.dbo.uspMyStoredProcedure")
        dbCommand.CommandTimeout = 300
        db.AddInParameter(dbCommand, "ClientID", DbType.String, ddlCompany.SelectedValue)
        db.AddInParameter(dbCommand, "startPeriod", DbType.String, ddlStartPeriod.SelectedValue)
        db.ExecuteDataSet(dbCommand)

        lblWarning.Text = "Please confirm that the <strong>ClientID and startPeriod </strong> are populated in the dropdown list."
        lblWarning.Visible = True
        lblConfirmation.Visible = False

    Catch ex As Exception
        valUpload.ErrorMessage = "There has been an unexpected error generating the page<br>(" + Err.Description + ")"
        valUpload.IsValid = False
    End Try
End Sub

2 个答案:

答案 0 :(得分:0)

我认为这里的问题是

db.ExecuteDataSet(dbCommand)

从我所看到的,您要运行的命令是

db.ExecuteNonQuery(dbCommand)

这是一个示例网站。代码在C#中,但我认为你可以对它有基本的了解。如果你真的需要,也可以使用翻译器。

http://msdn.microsoft.com/en-us/magazine/cc188702.aspx#S2

答案 1 :(得分:0)

我会把它改写成类似的东西:

Protected Sub RunValidation_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles RunValidation.Click
  Using cnn As New SqlClient.SqlConnection("MyConnection")
    cnn.Open()

    Using cmd As New SqlClient.SqlCommand("Company.dbo.uspMyStoredProcedure", cnn)
      cmd.CommandTimeout = 30
      cmd.Parameters.Add(New SqlClient.SqlParameter("ClientID", SqlDbType.NVarChar, 50) With {.Value = ddlCompany.SelectedValue})
      cmd.Parameters.Add(New SqlClient.SqlParameter("startPeriod", SqlDbType.NVarChar, 50) With {.Value = ddlStartPeriod.SelectedValue})

      Try
        cmd.ExecuteNonQuery()
      Catch ex As Exception
        valUpload.ErrorMessage = "There has been an unexpected error generating the page<br>(" + Err.Description + ")"
        valUpload.IsValid = False
      End Try

      lblWarning.Text = "Please confirm that the <strong>ClientID and startPeriod </strong> are populated in the dropdown list."
      lblWarning.Visible = True
      lblConfirmation.Visible = False

    End Using
  End Using
End Sub

一些注意事项:

  • 在try-catch中尽可能少地包装代码。在这种情况下,只有数据库应该引起关注(授予您验证输入)。
  • using statement非常巧妙地处理您的连接和命令对象以防出现问题。
  • 您可能希望进一步重构代码,将数据库调用部分保留在单独的函数/子中,并在其他位置设置标签和UI消息。