Start learning with our library of video tutorials taught by experts. Get started

Java Database Integration with JDBC

Filtering data with prepared statements


From:

Java Database Integration with JDBC

with David Gassner

Video: Filtering data with prepared statements

So far in this video series, I have shown you how to work with static SQL statements, statements that are the same when programmed, and when executed at runtime. But in many applications, you'll need to use parameterized SQL statements, statements where there are placeholders that you fill in with variable values at runtime. In JDBC, you do this with a class called PreparedStatement. The PreparedStatement class lets you set up an SQL statement as a string with these placeholders and then fill them in with variable values.
Expand all | Collapse all
  1. 5m 23s
    1. Welcome
      53s
    2. What you should know before starting this course
      1m 20s
    3. Using the exercise files
      3m 10s
  2. 12m 2s
    1. Testing your Java development environment
      5m 14s
    2. Importing a MySQL database
      5m 1s
    3. Creating a database user in MySQL
      1m 47s
  3. 32m 47s
    1. What is JDBC?
      4m 26s
    2. Choosing a JDBC driver
      6m 46s
    3. Connecting to a MySQL database server
      8m 7s
    4. Connecting to a HyperSQL database file
      6m 23s
    5. Executing a static SQL statement
      7m 5s
  4. 17m 42s
    1. Connecting to multiple databases
      6m 24s
    2. Handling JDBC exceptions
      7m 7s
    3. Closing database resources in Java 7
      4m 11s
  5. 47m 25s
    1. Looping through result sets
      8m 23s
    2. Moving the cursor in scrollable result sets
      5m 51s
    3. Limiting the number of fetched rows
      6m 57s
    4. Filtering data with prepared statements
      6m 58s
    5. Calling stored procedures
      5m 48s
    6. Handling multiple values from stored procedures
      5m 54s
    7. Using generic getter methods in Java SE 7
      7m 34s
  6. 45m 23s
    1. Managing data entities with JavaBean classes
      5m 0s
    2. Retrieving a single row as a JavaBean object
      6m 5s
    3. Inserting rows with prepared statements
      8m 2s
    4. Updating rows with prepared statements
      5m 4s
    5. Deleting rows with prepared statements
      4m 9s
    6. Managing data with updatable result sets
      6m 6s
    7. Using a persistent database connection
      6m 43s
    8. Committing and rolling back transactions
      4m 14s
  7. 9m 35s
    1. Getting the DatabaseMetaData object
      3m 40s
    2. Getting column and data type information
      5m 55s
  8. 50s
    1. Next steps
      50s

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
Please wait...
Java Database Integration with JDBC
2h 51m Intermediate Nov 28, 2012

Viewers: in countries Watching now:

Whether you're building a web- or desktop-based application with Java SE or Java EE, many Java applications need to integrate data from a relational database. This course describes how to read and manage data from relational databases such as MySQL and SQL Server using the Java Database Connectivity (JDBC) API.

Author David Gassner explains how to choose a JDBC driver and connect to one or more databases. He also provides detailed instructions on reading, selecting, and updating data; calling stored procedures; managing data via JavaBean classes or with prepared statements; and working with metadata.

Topics include:
  • Importing a MySQL database
  • Connecting to databases
  • Handling JDBC exceptions
  • Looping through result sets
  • Limiting the number of fetched rows
  • Filtering data with prepared statements
  • Calling stored procedures
  • Inserting, updating, and deleting rows with prepared statements
  • Using a persistent database connection
  • Committing and rolling back transactions
Subjects:
Developer Databases Programming Languages
Software:
Java
Author:
David Gassner

Filtering data with prepared statements

So far in this video series, I have shown you how to work with static SQL statements, statements that are the same when programmed, and when executed at runtime. But in many applications, you'll need to use parameterized SQL statements, statements where there are placeholders that you fill in with variable values at runtime. In JDBC, you do this with a class called PreparedStatement. The PreparedStatement class lets you set up an SQL statement as a string with these placeholders and then fill them in with variable values.

I'll demonstrate this in the project Prepared Statements. In this version of my console application, I have a static string representing the SQL statement. Right now, I'm retrieving all of the data from the Tours table. And then, when I display the data using this version of the displayData method, I'm first moving the ResultSet cursor to the end of the ResultSet, then getting the row to find out how many rows I got back. And then, if I got back zero, I say there were no tours found. And if I got back more than zero, I output the number and loop through and display the actual data.

I'll test this version of the application before I make any changes. And I see that I'm displaying all of the data from the database. Now let's change the requirements of our application. Let's say that the user is allowed to enter a numeric value representing the largest amount of money that they want to spend on a tour, and we want to retrieve only those tours where the price is less than or equal to the value that the user provides. The first step, I'll use a class named inputHelper that I have added to this project. In this version, in addition to the getInput method which returns a string, I have a method called getDoubleInput.

It calls the getInput method and then parses it and turns it into a double value. And if it fails because the end user enters a value that can't be parsed as a double, it throws an instance of number format exception. So going back to my main class, I'll place the cursor inside the main method right at the top, and I'll declare a new variable called maxPrice. Then I'll set up a try catch block. In the try block, I'll set the value of maxPrice using the inputHelper's static method getDoubleInput, and I'll display a prompt of enter a maximum price.

Within the catch section, if an error is thrown, I'll use a little bit of Error output, and I'll output a static string of Error: invalid number, and then I'll just clean up this try catch block so that instead of looking for the Exception object, I'll look for an instance of NumberFormatException. So now I have a value that I can plug into my SQL statement. I need to prepare the SQL statement to accept this variable value. I'll go up to the string where I'm setting the SQL statement, and I'll add a WHERE clause, and I'll use this syntax, WHERE price <= ? and then I'll put in a question mark.

Each time you add in a question mark, that's a placeholder for a variable value. In order to process this SQL statement, I need to add another class. Instead of statement, I'm going to use something called a PreparedStatement. The PreparedStatement is the JDBC class that knows how to process SQL statements with variable parameters. I'll place the cursor down within this try catch block, and I'll add Prepared to the beginning of the class name. Then to make sure that I have imported PreparedStatement, I'll move my cursor to the end of the name and press Ctrl+Space, and I'll choose the version of PreparedStatement that's a member of the java.sql package.

That adds an import statement at the top of the code. I'll open up my imports, and show that that was added correctly. Then I'll collapse them again. In order to instantiate a PreparedStatement object, instead of calling create statement, you call a method of the connection object, called prepareStatement. So, I'm going to change that code here. I'll call the prepareStatement method, and then in order to use this properly, before I pass in the type and the read-only setting, I'll pass in the SQL string as the first argument.

Then just as with a static statement, I'm setting the type so I can scroll, and I'm setting it to read-only. So now I have my PreparedStatement object. Before I execute the query, I have to fill in the placeholders or parameters. To do that, you call one of the many methods of the Statement object. For example, I'm filling in a double value, a numeric value that could have fractions. So, I'm going to set the value this way, stmt.set, and notice how many different Set methods there are.

Each of these methods takes an integer value and then the value you want to set. The parameters are indexed starting at one, not zero. I only have one parameter in MySQL statement, the price. So I'll choose the right method for my data type which is Double. I'll call setDouble. I'll pass in a value of 1, meaning I'm setting the first parameter, and then I'll pass in the maxPrice value as the value that I want to set. Notice that I'm getting a warning. I'll move the cursor over to the warning indicator, and it tells me that The local variable maxPrice may not have been initialized.

To fix that, I'll place the cursor within my catch block. And after I output the message that the user entered an invalid string that couldn't be parsed with a number, I'll return, and that will fix the flow of this code, so that now by the time I get to the code that's setting the double value, I'll know that the maxPrice is valid. Finally, I have one more change to make. When you use a PreparedStatement, you have already passed in the SQL string when you prepared the statement. So, you don't pass it in again when you execute it. So I'm going to remove SQL as an argument of the executeQuery method.

When I call executeQuery now, I'm working with the statement that already has the SQL, and that has already set its parameters. I'll save and run the code. When prompted, I'll click into the console, and I'll enter a value of 500. That means I want to see tours that cost less than or equal to $500. I get back 11 tours. I'll run the code again. This time, I'll pass in a value of $300. And I get fewer tours than I did the last time. I'll run it again.

This time I'll pass in $100. And I get back just one tour. And I'll run it one last time. And this time, I'll look for a really cheap tour, one that only costs $50. And I get back the message, no tours were found. You can set up your PreparedStatements with as many placeholders as you like and as many data types as you need to. Remember that there are many versions of the set method, one for each data type, so if you're working with an integer value in the database, use the setInt method, if you're working with a string, use setString, and so on and so forth.

The PreparedStatement interface is available for pretty much every database that has a JDBC driver. It lets you use parameterized SQL statements and greatly simplifies the process of creating applications that work with a database dynamically.

There are currently no FAQs about Java Database Integration with JDBC.

Share a link to this course
Please wait... Please wait...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Java Database Integration with JDBC.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Welcome to the redesigned course page.

We’ve moved some things around, and now you can



Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked