VB.NET连接必须有效并打开ERROR

时间:2014-11-28 14:39:33

标签: .net connection

我试图将MySQL数据库连接到我的VB.NET应用程序。只需登录表单。

我是初学者。所以我正在测试一个新项目。

当我点击“登录”按钮时,它显示“#34;连接必须有效并且打开!"

但是连接检查按钮(Button1)正在工作。

我不知道为什么......

这是源代码。我该如何解决?

Imports MySql.Data.MySqlClient

Public Class Form1
    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=localhost;userid=root;password=-------;database=user"

        Try
            Mysqlconn.Open()
            MessageBox.Show("Connection Successful.")
            Mysqlconn.Close()

        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            Mysqlconn.Dispose()

        End Try

    End Sub

    Private Sub loginbtn_Click(sender As Object, e As EventArgs) Handles loginbtn.Click
        Mysqlconn = New MySqlConnection
        Mysqlconn.ConnectionString =
            "server=localhost;userid=root;password=password;database=user"
        Dim READER As MySqlDataReader
        Try
            Mysqlconn.Open()
            Dim Query As String
            Query = "select * from user.Useridpw where UserID='" & Username.Text & "' and UserPW='" & Password.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("ID PW OK")
            ElseIf count > 1 Then
                MessageBox.Show("ID/PW Duplicated.")
            Else
                MessageBox.Show("ID/PW Incorrect.")

            End If

            Mysqlconn.Close()

        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            Mysqlconn.Dispose()

        End Try
    End Sub
End Class

1 个答案:

答案 0 :(得分:1)

一些问题

  1. 尚未将查询与命令

  2. 相关联
  3. 尚未将命令与连接相关联

  4. 连接是命令的属性,很多都是分配的 DbCommand.Connection Property