-1

嘿,我一直在努力寻找一些关于如何去做这件事的资源,但我找不到任何东西,因为,真的,我一开始真的不知道它会被称为什么。

有问题的代码是这样的:

Dim updateCmd As New SqlCommand(sql, myCONN)

有几个地方我需要在 IF THEN 结构内使用它。

但是,当我在 IF THEN 结构之外将其调暗时,它会告诉我(在 IF THEN 内部)它没有声明。

所以完整的例子是这样的:

If alreadyCreatedSettingsTable = False Then
   Dim updateCmd As New SqlCommand(sql, myCONN)

   updateCmd.Parameters.Add("@urlLink", SqlDbType.VarChar)
End If

rssItems = rssDoc.SelectNodes("rss/channel/item")

For i = 0 To rssItems.Count - 1
   rssDetail = rssItems.Item(i).SelectSingleNode("link")

   If rssDetail.Equals(Nothing) = False Then
      rssLink = rssDetail.InnerText.Trim
      updateCmd.Parameters("@urlLink").Value = rssLink
   End If
etc....

If alreadyCreatedSettingsTable = False Then dim 对于 updateCmd.Parameters.Add 工作得很好,但是它在For i = 0 To rssItems.Count - 1内时,它告诉我它没有被取消校准。

无论如何,我怎样才能在任何地方使用它并重新调整它?

我试过了

Dim updateCmd

But i then do not know how to set As New SqlCommand(sql, myCONN) since its already been Dim'ed already?

4

1 回答 1

3

Dim declares a variable. As New is just syntactic sugar; the scope of the variable is inside that If block. Declare it outside and initialize it inside:

Dim updateCmd As SqlCommand

If alreadyCreatedSettingsTable = False Then
   sql = "UPDATE jotSettings " & _
                        "etc etc...."

   updateCmd = New SqlCommand(sql, myCONN)

   updateCmd.Parameters.Add("@urlLink", SqlDbType.VarChar)
End If

rssItems = rssDoc.SelectNodes("rss/channel/item")

For i = 0 To rssItems.Count - 1
   rssDetail = rssItems.Item(i).SelectSingleNode("link")

   If rssDetail.Equals(Nothing) = False Then
      rssLink = rssDetail.InnerText.Trim
      updateCmd.Parameters("@urlLink").Value = rssLink
   End If

Also, please never write = False; use Not instead. Or, in the case of rssDetail.Equals(Nothing) = False, you almost certainly want rssDetail IsNot Nothing instead.

Finally, as written, this is pointless. If alreadyCreatedSettingsTable is True, you'll get a NullReferenceException when you use updateCmd.Parameters("@urlLink"). It seems to me that it's something that should be declared outside of a loop, or at class level - though that's just a guess.

P.S. Why are you overwriting updateCmd.Parameters("@urlLink") every time? That's wasteful.

于 2012-11-09T18:31:06.333 回答