Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB - MySql select from a database

Tags:

mysql

vb.net

This is how my form looks like - image.

When form loads, I would like to retrieve the player data whose username is in the Label1, so I could display its points in the Label2.

Here's my code so far:

Dim conn As MySqlConnection
conn = New MySqlConnection("server=REMOVED;Port=REMOVED; user id=REMOVED; password=REMOVED; database=REMOVED")
Dim username As Boolean = True
conn.Open()
Dim sqlquery As String = "SELECT Name FROM NewTable WERE Name='" & My.Settings.Name & "';"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = sqlquery
command.Connection = conn
adapter.SelectCommand = command
data = command.ExecuteReader
While data.Read()
    Label1.Text = data(1).ToString
    Label2.Text = data(3).ToString
End While

data.Close()
conn.Close()

Any help would be much appreciated.

like image 383
WireCoder Avatar asked Oct 03 '22 23:10

WireCoder


1 Answers

You should parameterized your query to avoid sql injection, Using for proper object disposal, Try-Catch block to handle the exception properly.

Dim connString As String = "server=REMOVED;Port=REMOVED; user id=REMOVED; password=REMOVED; database=REMOVED"
Dim sqlQuery As String = "SELECT Name, Points FROM NewTable WHERE Name = @uname"
Using sqlConn As New MySqlConnection(connString)
    Using sqlComm As New MySqlCommand()
        With sqlComm
            .Connection = sqlConn
            .Commandtext = sqlQuery
            .CommandType = CommandType.Text
            .Parameters.AddWithValue("@uname", My.Settings.Name)
        End With
        Try
            sqlConn.Open()
            Dim sqlReader As MySqlDataReader = sqlComm.ExecuteReader()
            While sqlReader.Read()
                Label1.Text = sqlReader("Name").ToString()
                Label2.Text = sqlReader("Points").ToString()
            End While
        Catch ex As MySQLException
            ' add your exception here '
        End Try
    End Using
End Using
like image 186
John Woo Avatar answered Oct 07 '22 20:10

John Woo