SQL Server VB.NET SQL conversion error when trying to read data

gdx19jrr  于 2023-03-11  发布在  .NET
关注(0)|答案(1)|浏览(144)

I'm trying to get data from a database but keep getting the following error.
Conversion failed when converting the varchar '102A' to data type int

The database table has 3 columns UserID , UserName , UserInfo , all of them defined as type varchar .

There is also a user in the table with ID 102A.

I'm trying to get the Username of the User with ID 10307.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim con As New SqlConnection
    Dim cmd As New SqlCommand
    Dim datareader As SqlDataReader

    con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Database.mdf;Integrated Security=True;User Instance=True"
    Try
        con.Open()
        cmd.Connection = con

        cmd.CommandText = "SELECT * FROM Users WHERE UserID = 10307"
        datareader = cmd.ExecuteReader
        datareader.Read()
        MsgBox(datareader.GetValue(2))
        datareader.Close()

        con.Close()
    Catch ex As SqlException
        MessageBox.Show(ex.Message)
    End Try
End Sub

I also tried to change datareader.GetValue to datareader.GetString but I get the same error.

Can anyone help me please, I've been stuck for days now...

Thank you

vq8itlhq

vq8itlhq1#

I think, you have to use datatable. You can use that example:

Dim dt As New DataTable

        Dim Connection As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Database.mdf;Integrated Security=True;User Instance=True")
        Dim Adapter As SqlDataAdapter
        Dim SourceDataSet As New DataSet()
        Dim myBuilder As SqlCommandBuilder = New SqlCommandBuilder

        SourceDataSet = New DataSet()

        SourceDataSet.Reset()

        Adapter = New SqlDataAdapter("SELECT * FROM Users WHERE UserID = 10307", Connection)
        Adapter.SelectCommand.CommandTimeout = 6000

        Adapter.Fill(SourceDataSet)

        dt = SourceDataSet.Tables(0)
        dim yourValue as object = dt.rows(0).Item([your field index or field name])

相关问题