连接必须有效并打开 VB.Net

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31316322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:16:42  来源:igfitidea点击:

Connection must be valid and open VB.Net

mysqlvb.net

提问by Donquixote Adiyatma

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

我想将我的 MySQL 连接到我的 VB.net。我只使用登录表单。我已经给出了代码,但代码给了我这个错误信息: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.

谁能帮我解决这个问题?谢谢。

回答by Daniel Waghorn

To associate your Queryand Commandwith the connection you need to do this:

要将您的QueryCommand与连接相关联,您需要执行以下操作:

Command = New MySqlCommand(Query, MysqlConn)

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

然后您可以执行操作来检索您需要的数据。

回答by Rowland Shaw

At no point do you associate your MysqlConnnor Queryto your Commandbefore trying to call ExecuteReaderon it. As such, it doesn't have a valid connection at that time.

在尝试调用它之前,您MysqlConn绝不会将您的或 Query与您的关联。因此,它当时没有有效的连接。CommandExecuteReader

回答by Ger.-

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

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