1

I've been trying to use an IF/ELSE statement to query my MySQL database, but can't seem to figure out why the ELSE statement is being ignored by VB. Here's the code - any help would be appreciated:

dbConn = New MySqlConnection("Server=" & FormLogin.ComboBoxServerIP.SelectedItem & ";Port=3306;Uid=qwertyuiop;Password=lkjhgfdsa;Database=zxcvbnm")
    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() = True Then
            MessageBox.Show("Customer Account Found!")
        Else
            MessageBox.Show("No Customer Records Found!  Please try again!")
            dbData.Close()
        End If
    End While

My intent is to replace the messagebox in the "IF" clause with the code that will populate my form with the data from the database.

Kismet Agbasi
  • 557
  • 2
  • 8
  • 28

2 Answers2

3

That's because you are already reading it:

While dbData.Read()
  If dbData.HasRows() = True Then
    MessageBox.Show("Customer Account Found!")
  Else
    MessageBox.Show("No Customer Records Found!  Please try again!")
    dbData.Close()
  End If
End While

If your reader has no records, the whole While loop will be skipped.

Try it the other way around:

If dbData.HasRows Then
  While dbData.Read()
    'looping through records here
  End While
Else
  MessageBox.Show("No Customer Records Found!  Please try again!")
End If

And also the obligatory note: Don't keep your connections open and alive. Use the Using End Using bracket to automatically close your disposable objects.

LarsTech
  • 80,625
  • 14
  • 153
  • 225
  • Thanks for your help. The suggestion worked like a charm - and thanks to you I've learned something new. But how would I use the USING END USING bracket - in my situation - to automatically open and close the connection? – Kismet Agbasi Aug 30 '12 at 20:04
  • @KismetAgbasi See [Does End Using close an open SQL Connection](http://stackoverflow.com/q/376068/719186). Also, learn to use parameters. Your sql query is ripe for sql injection and parameters would help prevent that. – LarsTech Aug 30 '12 at 21:22
0

I wouldn't say it's skipping your else clause, but it could be evaluating your if condition differently that you expect.

Personally, I don't like comparing anything to True. If you drop the = true, does it work?

Beth
  • 9,531
  • 1
  • 24
  • 43
  • Didn't get a chance to try your suggestion to drop the '= true'. I tried another suggestion from LarsTech and it worked - but thanks anyway Beth, I really appreciate it. – Kismet Agbasi Aug 30 '12 at 20:08