Reading data from database in vb.net

So, I used this piece of code to retrieve data from an MS Access database and display it in multiple text boxes on the form. The following error occurred:

@dr = cmd.ExecuteReader - data type mismatch in criteria expression. dr = cmd.ExecuteReader

This is a sample code -

Dim provider As String
Dim dataFile As String
Dim connString As String
Public myConnection As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
    dataFile = "C:\Users\example\Desktop\Data.accdb" ' Change it to your Access Database location
    connString = provider & dataFile
    myConnection.ConnectionString = connString
End Sub

Dim r As Random = New Random

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    myConnection.Open()
    TextBox1.Clear()
    TextBox2.Clear()
    TextBox3.Clear()
    Dim str As String
    str = "SELECT * FROM Items WHERE (Code = '" & r.Next(1, 3) & "')"
    Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
    dr = cmd.ExecuteReader
    While dr.Read()
        TextBox1.Text = dr("Description").ToString
        TextBox2.Text = dr("Cost").ToString
        TextBox3.Text = dr("Price").ToString
    End While
    myConnection.Close()
End Sub

      

+3


source to share


3 answers


The name of the table in the file you provided for download is "Table1", not "Items".

Change your query string to:



str = "SELECT * FROM Table1 where (Code = '" & r.Next(1, 3) & "')"

+1


source


Try it.



str = "SELECT * FROM Items WHERE (Code = '" and (r.Next (1, 3)). ToString () and "')"

+3


source


try this:

str = "SELECT * FROM Items WHERE (Code = '" and cStr (r.Next (1, 3)) and "')"

+2


source







All Articles