1
votes

I want to connect my MySQL to my VB.net. I am only using Login Form. I have given the code but the code gives me this error message: Connection must be valid and open

This is my code:

Imports MySql.Data.MySqlClient
Public Class Login 
    Dim MysqlConn As MySqlConnection
    Dim Command As MySqlCommand

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        MysqlConn = New MySqlConnection
        MysqlConn.ConnectionString ="server=db4free.net;port=3306;userid=exd****;password=****;database=exd****"
        Dim Reader As MySqlDataReader

    Try
        MysqlConn.Open()
        Dim Query As String
        Query = "select * from member where Username='" & UsernameTxt.Text & "' and Password='" & PasswordTxt.Text & "' "
        Command = New MySqlCommand
        Reader = Command.ExecuteReader
        Dim count As Integer
        count = 0

        While Reader.Read
            count = count + 1
        End While

        If count = 1 Then
            MessageBox.Show("Correct !")
        ElseIf count > 1 Then
            MessageBox.Show("Duplicate !")
        Else
            MessageBox.Show("Not Correct !")
        End If

        MysqlConn.Close()

    Catch ex As Exception
         MsgBox(ex.Message)
    Finally
        MysqlConn.Dispose()
    End Try

    End Sub

End Class

Can anyone help me to fix that? Thanks.

3
What did you try to solve this? This seems like we should debug you program. Also, please take a look at the tour and how to ask.moffeltje

3 Answers

2
votes

At no point do you associate your MysqlConn nor Query to your Command before trying to call ExecuteReader on it. As such, it doesn't have a valid connection at that time.

3
votes

To associate your Query and Command with the connection you need to do this:

Command = New MySqlCommand(Query, MysqlConn)

You can then perform operations to retrieve the data you need.

0
votes

Query = "select * from member where Username='" & UsernameTxt.Text & "' and Password='" & PasswordTxt.Text & "' ", nombredelaconexion