0

How to retrieve the data from Database in VB.net

I am using SELECT* FROM tbl1 WHERE Col1 = 'Chaitra'

My requirement is there is one Textbox, I have retrieved text from that textbox & assigns to a variable called str1.

Now I have to compare this variable with database (SELECT* FROM tbl1 WHERE Col1 = str1).

Can we write like this? or is there any other way to do this?

1 Answer 1

3

Use parameters to prevent Sql-Injection

Dim t As New DataTable()
Using c As New SqlConnection(connectionString)
      c.Open()
      Using a As New SqlDataAdapter("SELECT* FROM tbl1 WHERE Col1 = @Col1", c)
          'use the appropriate SqlDbType'
          a.SelectCommand.Parameters.Add("@Col1", SqlDbType.NChar, 5, "Col1")
          a.SelectCommand.Parameters("@Col1").Value = str1
          a.Fill(t)
      End Using
End Using
Return t

Edit: according to your comment that you want to query MS Access

Dim t as New DataTable
Dim adapter As OleDbDataAdapter = New OleDbDataAdapter()
Dim command As OleDbCommand

Using connection As New OleDbConnection(connectionString)
    ' Create the SelectCommand.
    command = New OleDbCommand("SELECT * FROM Users " & _
        "WHERE UserName = ?", connection)

    command.Parameters.Add("UserName", OleDbType.VarChar, 20).Value = userName 'userName is a string variable

    adapter.SelectCommand = command
    connection.Open()
    adapter.Fill(t) 't is the DataTable that holds all columns of the User
End Using

http://msdn.microsoft.com/en-us/library/bbw6zyha.aspx

Sign up to request clarification or add additional context in comments.

2 Comments

Sir, I can't understand the above code, since I am new to this field. I have one MS access database table having 3 columns (ID, Username & Password). If I enter the Username & Password in the respective TextBoxes, it should retrieve the ID of that particular record. So pls help me regarding this
@user: edited my answer to provide an exmaple on how to query a MS Access database with parameters. The result is a DataTable with one record(if there is one user with this UserName).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.