gpt4 book ai didi

mysql - 修复VB.NET错误 "Connection must be valid and open"

转载 作者:行者123 更新时间:2023-11-29 10:11:13 25 4
gpt4 key购买 nike

我在创建的登录表单中收到错误,内容是“连接必须有效且打开,有人可以帮助我吗?这是代码。我无法理解此错误是什么,我需要您的帮助.

Imports MySql.Data.MySqlClient
Public Class LoginForm1

Dim Username As String
Dim Password As String
Public StudentName As String
'MySql
Dim connection As New MySqlConnection("Server=server;User ID=id;Password=pass;Database=data;SSLMode=None")

Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click

Username = UsernameTextBox.Text
Password = PasswordTextBox.Text
StudentName = NameTextBox.Text

Dim command As New MySqlCommand("SELECT `Username`, `Password`, `FirstName` FROM `people` WHERE `Username` = @username AND `Password` = @password And `FirstName` = @name", connection)
command.Parameters.Add("@username", MySqlDbType.VarChar).Value = Username
command.Parameters.Add("@password", MySqlDbType.VarChar).Value = Password
command.Parameters.Add("@name", MySqlDbType.VarChar).Value = StudentName


Dim adapter As New MySqlDataAdapter(command)
Dim table As New DataTable()
Dim reader As MySqlDataReader = command.ExecuteReader

adapter.Fill(table)

If table.Rows.Count = 0 Then
MessageBox.Show("Invalid Username Or Password", "Invalid Login", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else

MessageBox.Show("Logged In", "Logged in Successfully", MessageBoxButtons.OK, MessageBoxIcon.Information)
MainMenuForm.Show()
Me.Close()
End If
End Sub

Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
Me.Close()
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim webAddress As String = "http://windowsadvancedstudy.com"
Process.Start(webAddress)
End Sub
End Class

最佳答案

如果您使用 adapter.Fill,则无需声明 reader。删除这一行:

Dim reader As MySqlDataReader = command.ExecuteReader

正是上面的行引发了异常。因为reader需要一个开放的连接。

并添加行:

command.CommandType = CommandType.Text

关于mysql - 修复VB.NET错误 "Connection must be valid and open",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50929196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com