在 .NET 中获取 MySQL 数据时出错

Error when getting MySQL data in .NET

我正在创建一个从数据库中检索数据的 .NET Web 应用程序。但是,当 运行 以下代码时,我不断收到以下错误。

Fatal error encountered during command execution.

InnerException 是 {"Parameter '?Username' must be defined."},但我可以看到 ?Username 已定义并且我知道 Session("Username") 是正确的并且存在。

这是代码。它在 SupervisorNameAdapter.Fill(SupervisorNameData, "Data") 行失败。

Dim SupervisorID As String = Session("Username")

    Dim qryGetSupervisorName As String = "select * from USERS where UserID = ?Username"

    Using cn As New MySqlConnection(ConfigurationManager.ConnectionStrings("ConnectionInfo").ConnectionString), cmd As New MySqlCommand(qryGetSupervisorName, cn)

        cmd.Parameters.AddWithValue("?Username", SupervisorID)

        cn.Open()
        cmd.ExecuteNonQuery()
        cn.Close()

        Dim SupervisorNameAdapter As New MySqlDataAdapter(qryGetSupervisorName, cn)
        Dim SupervisorNameData As New DataSet
        SupervisorNameAdapter.Fill(SupervisorNameData, "Data")

        If SupervisorNameData.Tables(0).Rows.Count = 0 Then

            MsgBox("An error has occured. Please refresh the page.", vbOKOnly, "Error!")

        Else

            SupervisorName.Text = SupervisorNameData.Tables(0).Rows(0).Item(1) & " " & SupervisorNameData.Tables(0).Rows(0).Item(2)

        End If

    End Using

有人知道为什么会这样吗?

您没有正确设置 MySqlAdapter 使用的命令。您只需传递命令文本字符串,适配器使用该字符串构建另一个缺少所需参数的命令

只需将您的代码更改为

Dim SupervisorID As String = Session("Username")
Dim qryGetSupervisorName As String = "select * from USERS where UserID = ?Username"

Using cn As New MySqlConnection(ConfigurationManager.ConnectionStrings("ConnectionInfo").ConnectionString), cmd As New MySqlCommand(qryGetSupervisorName, cn)

    cmd.Parameters.AddWithValue("?Username", SupervisorID)
    Dim SupervisorNameAdapter As New MySqlDataAdapter(cmd)
    Dim SupervisorNameData As New DataSet
    ....

End Using