2

I am very new to VB.net and I am finding it exceptionally difficult to pass an sql query result (string) into a variable.

No matter what I try, I can't seem to get anything but boolean output from my reader function.

I need to obtain staff "account type" from my staff table and then define that account type in a variable.

Any suggestions?

Thanks.

Sidewayz
  • 25
  • 1
  • 5

1 Answers1

4

Here is a good tutorial about using MySQL and VB together:

The piece from this that may be of interest to you:

Sub Main()

    Dim cs As String = "Database=testdb;Data Source=localhost;" _
        & "User Id=testuser;Password=test623"

    Dim conn As New MySqlConnection(cs)

    Try
        conn.Open()
        Dim stm As String = "SELECT * FROM Authors"
        Dim cmd As MySqlCommand = New MySqlCommand(stm, conn)
        Dim reader As MySqlDataReader = cmd.ExecuteReader()

        While reader.Read()
            Console.WriteLine(reader.GetInt32(0) & ": " _ 
                & reader.GetString(1))
        End While

        reader.Close()

    Catch ex As MySqlException
      Console.WriteLine("Error: " & ex.ToString())
    Finally
      conn.Close()
    End Try

End Sub

Note the MySqlDataReader (reader) object. This lets you get various types of data back. You need to know the column type you are reading, and use the appropriate method.

For example if you're reading a boolean, you would write:

reader.GetBoolean(0)

Or a DateTime:

reader.GetDateTime(0)

This example uses int arguments to represent the column number, but I find this less intuitive than using the column name. Fortunately MySqlDataReader supports column names as well:

reader.GetString("account_type")

The example doesn't show reading these values into variables, but it's fairly trivial:

Dim accountType As String
...
accountType = reader.GetString("account_type")

(This assumes that your account type column is a string.)

Hopefully this helps get you on the right track.

JYelton
  • 35,664
  • 27
  • 132
  • 191
  • Also see http://stackoverflow.com/questions/6998919/mysqldatareader-retrieving-null-value-problem-in-c-sharp for dealing with DBNULL values, it's for C# but applies just the same to VB. – JYelton Mar 15 '12 at 16:59
  • Thanks so much. reader.getstring("account_type") worked like a charm. I really appreciate your help. – Sidewayz Mar 16 '12 at 02:18