Question

Dim conStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\databaseVB\bakery.accdb"
        Dim conn As New OleDbConnection(conStr)
        Dim cmd As New OleDbCommand
        Dim reader As OleDbDataReader
        Dim Item(5) As String
        Dim key = TextBox1.Text

        conn.Open()
        cmd.Connection = conn
       1>>>>> 'cmd.CommandText = "SELECT * FROM Member WHERE number = 3"
       2>>>>> cmd.CommandText = "SELECT * FROM Member WHERE number = '" & key & "'"
        MessageBox.Show(cmd.CommandText)
        reader = cmd.ExecuteReader()
        While reader.Read
            Item(0) = reader("Number").ToString
            Item(1) = reader("FirstName").ToString
            Item(2) = reader("LastName").ToString
            Item(3) = reader("User").ToString
            Item(4) = reader("Pass").ToString
        End While
        MessageBox.Show(Item(1).ToString)
        conn.Close()

from 1>>> I can read Item in databaes from 2>>> I can not read Item

Was it helpful?

Solution

Try using a parameterized query string:

cmd.CommandText = "SELECT * FROM Member WHERE number = @Number"

After this add your parameters.

//cmd.Parameters.Add("@Number", SqlDbType.Int).Value = 3;
//It is better to use .TryParse(), incase your users write non numerical values in the Textbox
cmd.Parameters.Add("@Number", SqlDbType.Int).Value = (int)TextBox1.Text;

Additionally you need to watch your data types. 3 is of type int, but TextBox1.Text is of type string. You need to parse the string to int in order for it to work. This should do the trick and prevent ugly syntax juggling, while mixing strings and variables; And prevent you from SQL Injection attacks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top