Creating a Parameterized Query

Published 25 May 07 01:23 PM

I've been asked by a couple readers on how to pass parameters into a SQL statement to your database using the TableAdapters. I actually created a video on how to do this in the context of a search query (play video | download videoentire series). It's really easy to do this using the TableAdapter Query Configuration Wizard. Let's create a quick login form for an example.

I've got a table called Users in my database and I've created a Dataset called UsersDataset by opening up the Datasources window and adding a new datasource to my database. Then I created a form called LoginForm and from the Toolbox I dragged some labels and textboxes for the entry and a couple buttons, OK and Cancel, onto the form. I then set the PasswordChar property on the PasswordTextbox to "*". This indicates that the textbox should display this character instead of what the user types, but the value of the Text property will still be what the user enters.

(By the way, this example does NOT demonstrate a secure way of writing login forms. We'll be passing what the user enters directly into the database which stores the password in clear text. It is NOT safe practice to store clear text passwords in your database. I'll post a follow-up that talks about techniques we can use to protect users' passwords, especially if we need to store them in a database. For now, let's concentrate on how we add parameterized queries to our TableAdapters. UPDATE: Here's the follow up.)

Now at this point I build the project and in the WindowsApplication1 Components section at the top of the Toolbox I can now see the UsersDataset and the UsersTableAdapter listed (it's important that you build your project to get the components listed in the Toolbox). I drag the UsersTableAdapter onto the LoginForm which creates a component in the tray named UsersTableAdapter1.

So now that we've got that all set up, we're going to add a parameterized query to the UsersTableAdapter. First open up the UsersDataset and right-click on the TableAdapter in the designer and choose "Add Query".

This will open up the TableAdapter Query Configuration Wizard. First it asks you to choose a command type. Keep the default selected as "Use SQL Statement" and then click Next. Next it asks you to choose a query type. We're going to select the second option, to create a SELECT statement that returns a single value, not a result set.

Next we'll write the parameterized query as "SELECT COUNT(*) FROM Users WHERE UserName = @UserName AND Password = @Password". Then click Next and name the function "Login". This will create a TableAdapter method called Login that accepts a UserName and Password as a parameter and returns an Object which will be an Integer in our case since we're specifying to return the COUNT(*) of the rows that match the WHERE clause.

Now back to the LoginForm, we can double-click on the OK button to add a Click event handler.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _

    Handles Button1.Click

   

    Try

        If CType(Me.UsersTableAdapter1.Login(Me.UserNameTextBox.Text, _

                 Me.PasswordTextBox.Text), Integer) > 0 Then

 

            MsgBox("Welcome to my application!")

        Else

            MsgBox("Invalid username or password.")

        End If

 

    Catch ex As Exception

        MsgBox(ex.ToString)

    End Try

End Sub

Now when we run this example and enter a user name and password that is contained in the database table Users, we get the greeting message otherwise we get the message that our user name or password is invalid.

As you can see it's really easy to add parameterized queries to your TableAdapters using the wizards. There's even a simple query builder you can use to help you write your queries and test them out before they are generated on the TableAdapter. In a follow up post I'll show you how to add secure password storage to your application using hashing and encryption.

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Murat Özcan said on May 26, 2007 4:32 PM:

Thanks Beth.

You're the best one.

# Glen said on May 27, 2007 6:19 PM:

Thanks from a noob....

Your videos are great!  Make a thousand more.  After programming in unix for the last several years.  I feel like I have been in a desert  and suddenly came across a well of water.

# Cesar said on May 27, 2007 8:38 PM:

Hi i need your help i have this error " Error 1 'login' no es un miembro de 'WindowsApplication1.UniversidadDataSetTableAdapters.usuariosTableAdapter'. C:\Documents and Settings\Käsar\Mis documentos\Visual Studio 2005\Projects\Cesar_University\Cesar_University\login.vb 5 22 Cesar_University"

What is Login??????If CType(Me.UsuariosTableAdapter1.login(

# alik levin's said on May 28, 2007 12:10 AM:

Creating parameterized queries is one of the major countermeasures to SQL Injection attacks (not the

# Beth Massi said on May 29, 2007 6:01 PM:

Hi Cesar,

The Login method is generated on the TableAdapter when you name the function "Login" after you enter your parameterized query in the wizard.

-B

# Beth Massi - Sharing the goodness that is VB said on June 7, 2007 1:47 AM:

In my first post on parameterized queries I built a simple login form that really was a contrived example

# Beth Massi - Sharing the goodness that is VB said on June 7, 2007 1:48 AM:

In my first post on parameterized queries I built a simple login form that really was a contrived example

# Beth Massi - Sharing the goodness that is VB said on June 14, 2007 12:15 AM:

I've been heads down this week (re)learning an older technology -- Visual Basic 6! With all the things

# Edy Kulinski said on June 17, 2007 6:50 PM:

Beth Great Job!

Help me!

In your first video you creat a stored procedures.

My VS 2005 don´t create in toolbox options for insert update and delete ?

What is wrong?

São Paulo - Brasil  whait your visit.

Thank you!

# Beth Massi said on June 18, 2007 5:24 PM:

Hi Edy,

Stored procedures are not created automatically for you. I wrote the stored procedures for the video and put them as snippets in the toolbox. You can create code snippets by selecting text in the code editor and then dragging that onto the toolbox. Then you can use that snippet of code again by dragging from the toolbox into the editor.

Cheers,

-B

# ahan said on June 27, 2007 4:23 PM:

I cannot locate WindowsApplication1 Components inthe ToolBox

I am Using VB 2005 Professional

THanks IN Advance

# Beth Massi said on June 27, 2007 5:17 PM:

Hi Ahan,

Make sure you build your project first.

"(it's important that you build your project to get the components listed in the Toolbox)"

-Beth

# Perry said on June 27, 2007 7:43 PM:

A small variation on your project, I would like the

user to enter values into two text boxes and use them

as range parameters in the dataset and return those records between the two values.  How would I do that?

# Beth Massi said on June 27, 2007 9:32 PM:

Hi Perry,

You can add as many parameters as you like to the query. Just like I showed above, when you add the @Parameter1 to the SQL query then it will pick it up as a parameter. If you are using Access (the OleDb client) then the parameter placeholder is a question mark (?). All you need to do is write the query that selects the range of values you want. For information on writing T-SQL queries check out SQL Server Books Online: http://msdn2.microsoft.com/en-us/library/ms130214.aspx

Cheers,

-B

# ahan said on June 28, 2007 7:31 AM:

I am Lost.

now after connecting My form to my DataBase, i can see an Application Components But it is connecting me to the data Base that i have created NOT the username/password.

# Perry said on June 28, 2007 11:16 AM:

How and where do you transfer the value from the text boxes or controls on your form the parameters themselves?

# Beth Massi said on June 28, 2007 12:29 PM:

Ahan,

Watch the video referenced at the top of the post for a step-by-step on creating a parameterized query. You create them on the TableAdapters which connect to your database and fill a DataTable -- but you can create the DataTable from any query.

# Beth Massi said on June 28, 2007 12:29 PM:

Perry,

The TableAdapter handles this for you when you call Me.UsersTableAdapter1.Login(Me.UserNameTextBox.Text,             Me.PasswordTextBox.Text)

# Perry said on June 28, 2007 5:35 PM:

Thank you so much for your help, its hard being a rookie sometimes.

# Eric said on July 23, 2007 9:05 PM:

Hi beth...thanks you for all ur video they make very useful to me.....but when i trying to do the login form they give me an error,

The wizard detected the follwing problems when configuring tableadapter query "user":

Details:

Generated Select Statement.

Error in from clause near 'USER'.

Unable tp parse query test.

To apply these settings to you query, click finish.

Can u help...i have following all the setup up in the page...

My db Name is USER

My variable is Userid and Password,

and my code is

SELECT COUNT(*) FROM USER where userid = @userid and password = @password

can u help me please

# Eric said on July 23, 2007 9:18 PM:

I find the error i need to Put dbo.[user]

# bobby said on July 29, 2007 1:21 PM:

I love you you have been the best guide for teaching these video tutorials

I just love you for being there always

thanks

Bobby

# Curtis Ward said on November 1, 2007 10:51 AM:

Hey there Beth you are the best. I have i little code that i need to perpare for an access database, for username and password this will be my start up page. Thanks. My email address is curtis_18u@hotmail.com

# Mike said on February 13, 2008 5:54 AM:

It works very well thanks Beth, in my database I have two tables admin and user the admin works fine admin id is a nchar but the user id uses int, so if I don't put anything in the box I get an exeption error invalidcastExeption conversion from string to type integer not valid? any sugestions

thanks in advance

# Crystalelle said on March 5, 2008 12:04 PM:

I just want to express my gratitude to you for writing this. You save my project. Thank you.

# Trevor said on May 22, 2008 12:31 PM:

Hi Beth,

How would you give the user three wrong attempts before kicking the application out completely?  I've tried various 'if' statements but to no avail - i'm just trying to do a standard

'if attempts<3'

try again

else

quit

endif

thanks again - these guys are 100% right - your videos and foundational teaching really peel away the mystery of VB for those of us first starting out.

# Teo said on June 4, 2008 6:17 AM:

Hi Beth,

I had tried on the login form and it works well the first time, when I tried again, I would not get any response when

username and password are correct,but when they are wrong, the responds is working, what could be wrong?

Thank you very much.

# Owen said on July 10, 2008 12:11 PM:

Beth I have found your tutorials very useful thanks!

I have a question for you. I am trying to set up a query that searches for matching ints. In the very same way that LIKE @Title would find a identicle "title" String. What syntax do you use in the filter box to do that comparsion? I keep getting data type errors.

Any help you could provide would be greatly helpful!

# Beth Massi said on July 21, 2008 12:46 PM:

Hi Owen,

The query syntax would be the same but instead you would pass an integer to the query method generated on the TableAdapter.

HTH,

-B

# Murat said on July 22, 2008 3:26 PM:

How do we activate Enter key press event ?

do we write the same code for that event or create a procedure or function

# peter said on July 23, 2008 10:11 AM:

hi, the steps are just very clear, i followed it and was able to create my login form. thanks for the good work massi.

could you please tell me how create a form that will change my password that is in the database now.

plaese, will be very greatfull if you reply to my url

# Bill Wright said on August 8, 2008 3:51 PM:

Hi Beth,

I'm a big fan.... I could use your help in converting the login app to an Web-app. Under vb 2005, I could not figure how to create a usertableadaptor.

# Prasad said on August 13, 2008 1:32 PM:

How do I execute a parameterized query using Access instead of SQL Server

Your videos are great.

Thx.

# freddi said on September 16, 2008 4:28 AM:

Hi Beth,

Thank for form over data series,... i learn a lot

please help,..

i create from with parent and child relation, it work fine to save in their table.

my problem is, i need to save the result to another new table with new ID,

is there any series to learn about it

thank you

# meltut said on February 25, 2009 8:00 AM:

thank you beth! this simple query may help me a lot to finish my documentation for thesis

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required

About Beth Massi

Beth is a Program Manager on the Visual Studio Community Team at Microsoft and is responsible for producing and managing content for business application developers, driving community features and team participation onto MSDN Developer Centers (http://msdn.com), and helping make Visual Studio one of the best developer tools in the world. She also produces regular content on her blog (http://blogs.msdn.com/bethmassi), Channel 9, and a variety of other developer sites and magazines. As a community champion and a long-time member of the Microsoft developer community she also helps with the San Francisco East Bay .NET user group and is a frequent speaker at various software development events. Before Microsoft, she was a Senior Architect at a health care software product company and a Microsoft Solutions Architect MVP. Over the last decade she has worked on distributed applications and frameworks, web and Windows-based applications using Microsoft development tools in a variety of businesses. She loves teaching, hiking, mountain biking, and driving really fast.

This Blog

Syndication

Page view tracker