Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
TitleExecute a parameterized query in VB .NET
Keywordsdatabase, VB.NET, parameter, parameterized query, query
CategoriesVB.NET, Database
 
Compose the query, replacing the values you want to be parameters with question marks. Use the query to build a command object.

Use the command's Parameters.Add method to add parameter objects to the command. The database will replace the question marks with the parameters in the order in which they are added. In other words, the first question mark is replaced with the first parameter, and so forth.

Execute the command and process the results as usual.

 
Private Sub DisplayPersonData(ByVal first_name As String, _
    ByVal last_name As String)
    ' Open the connection.
    connUsers.Open()

    ' Make a Command for this connection
    ' and this transaction.
    Dim cmd As New OleDb.OleDbCommand( _
        "SELECT * FROM People WHERE FirstName=? AND " & _
            "LastName=?", _
        connUsers)

    ' Create parameters for the query.
    cmd.Parameters.Add(New _
        OleDb.OleDbParameter("FirstName", first_name))
    cmd.Parameters.Add(New OleDb.OleDbParameter("LastName", _
        last_name))

    ' Execute the query.
    Dim db_reader As OleDbDataReader = _
        cmd.ExecuteReader(CommandBehavior.SingleRow)

    ' Display the results.
    If db_reader.HasRows Then
        db_reader.Read()
        txtFirstName.Text = _
            db_reader.Item("FirstName").ToString
        txtLastName.Text = _
            db_reader.Item("LastName").ToString
        txtStreet.Text = db_reader.Item("Street").ToString
        txtCity.Text = db_reader.Item("City").ToString
        txtState.Text = db_reader.Item("State").ToString
        txtZip.Text = db_reader.Item("Zip").ToString
    Else
        For Each ctl As Control In Me.Controls
            If TypeOf ctl Is TextBox Then ctl.Text = ""
        Next ctl
    End If

    ' Close the connection.
    connUsers.Close()
End Sub
 
For lots more information on database programming in VB .NET, see my book Visual Basic .NET Database Programming.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated