【问题标题】:InvalidCastException when retrieving data from SqlDataReader从 SqlDataReader 检索数据时出现 InvalidCastException
【发布时间】:2018-05-01 08:39:40
【问题描述】:

我怎样才能摆脱:

System.InvalidCastException: '从字符串“类型”转换为类型 '整数' 无效。'"

上线:

Dim usertype = Reader.GetString("Type")

这是我的完整代码:

Private Sub OKbt1_Click(sender As Object, e As EventArgs) Handles OKbt1.Click
    Call Connect() ' [ connection to module ]'
    Dim Reader As SqlDataReader

    Try
        Dim command As New SqlCommand("select * from uinfo where password = '" & PASStb2.Text & "'", sqlConn)
        Reader = command.ExecuteReader
        Reader.Read()

        Dim count As Integer = 0

        While Reader.Read
            count = count + 1
        End While

        If count = 1 Then

            ' ** MY ERROR **
            Dim usertype = Reader.GetString("Type")

            If usertype = "admin" Then
                'MsgBox("username and password are correct")
                MAIN_MENU.Show()

                For a = 0 To 500

                Next
                Me.Hide()
                sqlConn.Close()
                sqlConn.Dispose()

            ElseIf usertype = "user" Then

                For a = 0 To 500

                Next
                Me.Hide()
                'MsgBox("username and password are correct")
                USERMENU.Show()

            End If

        ElseIf count > 1 Then
            MsgBox("username and password are duplicate")

        Else
            MsgBox("username and password are not correct")
        End If

        sqlConn.Close()

    Catch ex As SqlException
        MsgBox(ex.Message)

    Finally
        sqlConn.Dispose()

    End Try
End Sub

【问题讨论】:

  • Declare usertype as Dim usertype as String

标签: sql vb.net runtime


【解决方案1】:

SqlDataReader.GetString Method (Int32) 需要一个整数(列索引)作为参数。所以你需要

Dim usertype as String = Cstr(Reader("Type"))

Dim usertype = Reader.GetString(Reader.GetOrdinal("Type"))

Dim usertype = Reader.GetFieldValue(Of String)("Type")

请注意,这些可能性中没有一个可以处理 DBnull。

【讨论】:

  • 谢谢队友 :) 很大的帮助没有注意到我使用 INT32 所以我检查了它,现在正在工作谢谢队友.. hoooray
【解决方案2】:

'Reader.GetString' 接受整数参数,而不是字符串。或者,做

Reader.Item("Type").ToString()

【讨论】:

  • 我试了一下,但弹出这个错误 System.InvalidOperationException: 'Invalid attempt to read when no data is present.'
【解决方案3】:

将 usertype 声明为 Dim usertype as String,然后像 usertype = Reader.Item("Type").ToString() 一样为其赋值。 您还需要检查 Reader.GetString("Type") 返回的值,它可能为空。开启“Option Strict”从长远来看会有所帮助。

【讨论】:

  • 我试了一下,但弹出此错误 System.InvalidOperationException: '在不存在数据时尝试读取无效。
  • @Hardik 检查为什么它为空。检查列名是否与数据库中的相同或该列是否包含任何数据
【解决方案4】:
 **Dim usertype = Reader.GetString("Type") // MY ERROR**

您传递的字符串值显然是错误的

GetString 函数接受整数。 您可能希望实例化一个整数数据并通过 getstring 传递它。

Dim usertype = Reader.GetString(data)

【讨论】:

    【解决方案5】:

    使用参数。我让服务员统计。为您节省几行代码。

    Private Sub OKbt1_Click(sender As Object, e As EventArgs) Handles OKbt1.Click
            Call Connect() ' [ connection to module ]'
            Dim Reader As SqlDataReader
            Try
                Using cmd As New SqlCommand("select usertype, Count(*) from uinfo Group By usertype where [password] = @password;", sqlConn)
                    cmd.Parameters.Add("@password", SqlDbType.VarChar).Value = PASStb2.Text
                    Reader = cmd.ExecuteReader()
                    If Reader.HasRows Then
                        Reader.Read()
                        Dim usertype As String = Reader.GetString(0)
                        Dim count As Integer = Reader.GetInt32(1)
                        If count = 1 Then
                            If usertype = "admin" Then
                                MAIN_MENU.Show()
                                Hide()
                            ElseIf usertype = "user" Then
                                USERMENU.Show()
                                Hide()
                            End If
                        ElseIf count > 1 Then
                            MsgBox("username and password are duplicate")
                        End If
                    Else
                        MsgBox("username and password are not correct")
                    End If
                End Using
            Catch ex As Exception
                MsgBox(ex.Message)
            Finally
                sqlConn.Close()
                sqlConn.Dispose()
            End Try
        End Sub
    

    【讨论】:

      【解决方案6】:

      这是因为您可能无法正确地从“Reader”对象中获取数据

      试试这个:

      Dim command As SqlCommand = New SqlCommand("SELECT  * FROM uinfo WHERE  password = '" & PASStb2.Text & "'", connection)
          connection.Open()
          Dim READER As SqlDataReader = command.ExecuteReader()
          If READER.HasRows Then
              While READER.Read()
                  Console.WriteLine("{0}" & vbTab & "{1}", READER.GetInt32(0), READER.GetString(1))
              End While
          Else
              Console.WriteLine("No rows found.")
          End If
      
          READER.Close()
      

      【讨论】:

      • 我认为 OP 使用的是 vb.net 而不是 C#
      猜你喜欢
      • 1970-01-01
      • 2021-12-05
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多