转换类型整数误解

时间:2013-02-23 18:36:25

标签: vb.net

我很抱歉我的英语不好。我希望有人可以解释错误The conversion from type MySqlDataReader to type Integer is invalid的含义。

我确信这是一个简单的'Dim a Integer,但它比那个大,或者我只是愚蠢。

我的btnLogin_Click代码:

Dim SQL As New MySQLHook
Dim loginResult As Integer

Dim User As TextBox = Me.Controls.Item("TextGebruikersNaam")
Dim Pass As TextBox = Me.Controls.Item("TextGebruikersPass")

If String.IsNullOrEmpty(User.Text) Or String.IsNullOrEmpty(Pass.Text) Then
    MsgBox("Voer een gebruikersnaam en wachtwoord in om verder te gaan.", MsgBoxStyle.Exclamation, "Foutmelding")
    User.Focus()
Else
    loginResult = SQL.Results("SELECT * FROM tblgebruikers " & "WHERE GebruikersNaam='" & User.Text & "' AND " & "GebruikersPass='" & Pass.Text & "'")

    If loginResult = 1 Then
        ' Login was good, todo: add code here
    Else
        MsgBox("De gebruikersnaam of wachtwoord is onjuist. Probeer het opnieuw of vraag een nieuw wachtwoord aan.", MsgBoxStyle.Exclamation, "Foutmelding")
        User.Text = ""
        Pass.Text = ""
        User.Focus()
    End If
End If

我的结果代码(SQL.Results来自As New MySQLHook)

Public Function Results(ByVal sql)
    Try
        Dim conn = Connect()

        Dim myAdapter As New MySqlDataAdapter
        Dim myCommand As New MySqlCommand()

        myCommand.Connection = conn
        myCommand.CommandText = sql

        myAdapter.SelectCommand = myCommand

        Dim myData As MySqlDataReader

        myData = myCommand.ExecuteReader()
        Return myData
    Catch myerror As MySqlException
        clsError.logMessage("De server retourneerde de volgende foutmelding: " & myerror.Message)
        Return DBNull.Value
    End Try
End Function

我尝试使用此功能,但它给了我相同的错误消息:

Public Function num_results(ByVal sql)
Try
    Dim conn = Connect()

    Dim myAdapter As New MySqlDataAdapter
    Dim myCommand As New MySqlCommand()

    myCommand.Connection = conn
    myCommand.CommandText = sql
    myAdapter.SelectCommand = myCommand

    Dim myData As MySqlDataReader

    myData = myCommand.ExecuteReader()
    Return myData
Catch myerror As MySqlException
    clsError.logMessage("De server retourneerde de volgende foutmelding: " & myerror.Message)
    Return DBNull.Value
End Try
End Function

为什么此转换错误弹出窗口?我确信1或0是自我解释的。

1 个答案:

答案 0 :(得分:1)

您的问题是您正在创建data reader并将其返回。在返回之前,您需要从myData变量中读取整数。

所以,而不是:

Return myData

你应该可以使用:

Return myData.GetInt32(0)

该语句中的0标识您要读取的列,并且由于您从SQL查询返回单个列,因此它位于索引0中。

修复后,谷歌“SQL注入”和“参数化SQL查询”,然后再继续。让您的应用程序对SQL注入开放是一个严重的风险。