2012-10-11 41 views
0

我有一个嵌入的IF语句应该在数据库查询后执行。但是,我在运行时注意到整个声明根本没有被评估(While dbData.Read()之后)。我究竟做错了什么?如果我的语句被跳过,会导致什么?

下面的代码:

Private Sub ButtonNew_Click(ByVal sender As System.Object, ByVal e As  System.EventArgs) Handles ButtonNew.Click 

If TextBoxSearch.Text = "" Then 
     MessageBox.Show("Sorry, you must enter an ACCOUNT# before proceeding!") 
     TextBoxSearch.Focus() 
    Else 
     Try 
      Dim dbConn As MySqlConnection 
      dbConn = New MySqlConnection("Server=" & FormLogin.ComboBoxServerIP.SelectedItem & ";Port=3306;Uid=parts;Password=parts;Database=accounting") 
      Dim account As Boolean = True 
      If dbConn.State = ConnectionState.Open Then 
       dbConn.Close() 
      End If 
      dbConn.Open() 
      Dim dbQuery As String = "SELECT * FROM customer WHERE accountNumber = '" & TextBoxSearch.Text & "';" 
      Dim dbData As MySqlDataReader 
      Dim dbAdapter As New MySqlDataAdapter 
      Dim dbCmd As New MySqlCommand 
      dbCmd.CommandText = dbQuery 
      dbCmd.Connection = dbConn 
      dbAdapter.SelectCommand = dbCmd 
      dbData = dbCmd.ExecuteReader 
      While dbData.Read() 
       If dbData.HasRows Then 
        'MessageBox.Show("Customer record already exists!") 
        Call recordExists() 
        account = False 
        Call lockForm() 
        TextBoxSearch.Focus() 
        Me.Refresh() 
       Else 
        'dbData.Close() 
        account = True 
        TextBoxAccount.Text = TextBoxSearch.Text 
        TextBoxAccount.BackColor = Color.LightGray 
        TextBoxAccount.TabStop = False 
        Call unlockForm() 
        TextBoxLastName.Focus() 
        ButtonSubmit.Visible = True 
        Me.Refresh() 
       End If 
      End While 
      dbData.Close() 
      dbCmd.Dispose() 
      dbAdapter.Dispose() 
      dbConn.Close() 
     Catch ex As Exception 
      MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _ 
         vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.") 
     End Try 
    End If 

End Sub 
+1

是有行? – rerun

+0

我正在测试(至少这是我希望做的)。如果搜索字段不是空的,则查询运行。我想测试该帐户是否已经存在。如果确实如此,则会显示一条消息,表明字段保持锁定状态。事实恰恰相反。但在进行调试时,一旦它进入While语句,就会退出,甚至不会评估While语句中的if语句。 –

回答

1

如果dbData.Read()回报False,那么它不会进入你的循环,因此If声明将不会被执行。如果没有要读取的行,那么Read总是返回False,所以If语句无用处。你需要移动If声明向上,以便在while循环是If块内:

If dbData.HasRows Then 
    While dbData.Read() 
     ' ... 
    End While 
Else 
    ' ... 
End If 
+0

谢谢Steven,我会试试这个,然后回报。 –

+0

再次感谢,我意识到我甚至都不需要While语句,所以我把它吹掉了,只是使用了IF/ELSE语句,并且它像魅力一样工作。谢谢。 –