gpt4 book ai didi

VB.net 中的 MySQL 连接错误

转载 作者:行者123 更新时间:2023-11-29 22:35:11 24 4
gpt4 key购买 nike

我尝试将 vb.net Webform 连接到 MySQL 数据库,但在运行时出现以下错误:

System.InvalidOperationException: Connection must be valid and open. at MySql.Data.MySqlClient.MySqlCommand.Throw(Exception ex) at MySql.Data.MySqlClient.MySqlCommand.CheckState() at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior) at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()

这是我的代码:

        Dim Sqlconnection As New MySqlConnection("server=localhost;user id=orderadmin;password=***;database=pfrorder")
Dim sqladapter As New MySqlDataAdapter
Dim cmd As New MySqlCommand
Dim reader As MySqlDataReader

cmd.CommandText = "SELECT * FROM orders"
cmd.CommandType = CommandType.Text
Sqlconnection.Open()
reader = cmd.ExecuteReader
Sqlconnection.Close()

最佳答案

命令、适配器或读取器完成其​​任务需要使用开放连接。您已打开连接,但没有将其与 MySqlCommand 关联。因此,当您调用 ExecuteReader 时,它不知道如何访问您的数据库。要解决此问题,只需使用接受 sql 文本和连接的 MySqlCommand 构造函数

Using connection = New MySqlConnection("...."=
Using cmd = New MySqlCommand("SELECT * FROM orders", connection)
connection.Open()
Using reader = cmd.ExecuteReader
.... do you stuff reading values from the reader here ...
.... if you close the connection, the reader is also closed ....
End Using
End Using
End Using

另请注意,每个一次性对象(如连接、命令或读取器)在您不再需要时应始终将其丢弃。 Using Statement确保您的对象在出现异常时也被关闭和处置,

(我还将 MySqlConnection 变量的名称更改为与 Sql Server SqlConnection 类相比更不易混淆的名称)

关于VB.net 中的 MySQL 连接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29570721/

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