简体   繁体   中英

VB.net data retrieval and display

So, for some reason I can't work out I think the below is only retrieving the 1st letter of the value within the column I'm trying to search. ( Note : the database is called m1 and contains 11 columns in total).

I tested the query first in SQL Admin and it worked properly (I think).

在此处输入图片说明

I then wrote this myself using documentation, I think I've more that likely made a mistake somewhere..

Dim hostnameQuery As String = "SELECT `HOSTNAME` FROM `m1` WHERE 1"
    Dim SQLConnection As New MySqlConnection(My.Settings.connStr)
    Dim cmd As New MySqlCommand(hostnameQuery, SQLConnection)

    Try
        SQLConnection.Open()
        cmd.ExecuteNonQuery()
        Dim reader As MySqlDataReader
        reader = cmd.ExecuteReader
        While reader.Read
            main.Label64.Text = (reader.GetChar(0))
        End While
    Catch ex As Exception
        MsgBox(ex.Message.ToString)
    Finally
        SQLConnection.Close()

    End Try

I added this to a button click so when I click the button only the letter 'M' appears but the value is 'M1'

在此处输入图片说明

What have I done wrong?

That's because you requested only a character. Try using GetString() instead of GetChar() :

main.Label64.Text = (reader.GetString(0))

There are many things that can be improved in your code.

First of all, you can remove the condition WHERE 1 , because it means "EVERYTHING" so it is not useful.

Secondly, you can avoid calling cmd.ExecuteNonQuery() because it is usually used to run an instruction that does not return anything (like INSERT ).

Finally, if you are interested only to the first returned row, you can avoid the While loop and use cmd.ExecuteScalar() instead.

To summarize, instead of:

cmd.ExecuteNonQuery()
Dim reader As MySqlDataReader
reader = cmd.ExecuteReader
While reader.Read
    main.Label64.Text = (reader.GetChar(0))
End While

simply do this:

main.Label64.Text = Convert.ToString(cmd.ExecuteScalar())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM