2012-10-11 75 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語句,並且它像魅力一樣工作。謝謝。 –