Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Executing a static SQL statement

From: Java Database Integration with JDBC

Video: Executing a static SQL statement

Once you have connected to a database, the next step is typically to send a request, and the most common sort of request is a simple SQL statement that retrieves data from the database. I'll show how to do this using the Statement interface and another interface named ResultSet, which encapsulates the data that's returned from the database. I'm working in a project called StaticSQL. This project's main class already has the code to connect to the database. It has the three strings, the User name, Password, and Connection string.

Executing a static SQL statement

Once you have connected to a database, the next step is typically to send a request, and the most common sort of request is a simple SQL statement that retrieves data from the database. I'll show how to do this using the Statement interface and another interface named ResultSet, which encapsulates the data that's returned from the database. I'm working in a project called StaticSQL. This project's main class already has the code to connect to the database. It has the three strings, the User name, Password, and Connection string.

And I'm working with an HSQLDB database. In addition to the connection, I also need an instance of Statement and an instance of ResultSet. When you call methods of these interfaces, just as with the methods of the Connection class, they might throw an SQL exception. So typically, you'll declare the objects outside of the try block and then execute their methods within the try block, and that will make them have the lifetime invisibility that you need. I'll move my cursor after the Connection declaration, and I'll declare a Statement.

I'll type in the name of the interface and press Ctrl+Space, and I'll choose the version of statement from java.sql. Again, my goal is to make this code as portable between databases as possible. I'll name this object stmt and set it to null. Next, I'll declare my ResultSet, and again, this is the interface that will contain the data returned from the database. I'll name that RS, and again, I'll set it initially to null. Now I'm ready to create my statement. I will move the cursor after the code that's connecting to the database, and I will make a little bit of space.

I'll instantiate the statement using this code, stmt, the name of the object, equals conn.create statement. Notice that there are a few different versions of the create statement method. A default Statement object is returned when you don't pass in any arguments. There's also a version of the method where you can set the type of the ResultSet and its concurrency, and that's the version that I'm going to use. The default ResultSet type will differ from one database to another. With MySQL, the default ResultSet object is scrollable. That means that you can move the cursor up and down, going to the first row, the last row, and moving around as you like.

But with many databases, including HSQLDB, the default ResultSet type is forward only, meaning that the cursor will start before the data, and you'll be able to move forward to the end, but you won't be able to move back again. I'd like to set up my code to override that default and get a ResultSet that's scrollable. So I'm going to set the ResultSet type to a constant that looks like this. ResultSet, and I'll choose the constant TYPE_SCROLL_INSENSITIVE. That means that it's scrollable, but it won't be sensitive to any changes in the underlying data.

Essentially, it's a read-only ResultSet. Now I also need to set something called resultSetConcurrency, and this will indicate whether I'm working with a read-only ResultSet or an updatable ResultSet, a ResultSet that has a live connection to the underlying database. For the best performance, if I'm only going to be reading the data, I'll set the ResultSet to read-only, and I'll do that with another constant of ResultSet called CONCUR_READ_ONLY. So now I have created my statement object, and I'm ready to send the request to the database.

I'll instantiate my rs or ResultSet object, and I'll get data back by calling the Statement object, executeQuery method. When you call executeQuery, you can pass in any StaticSQL string. The nature of the SQL command is determined by the database you're working with. There's a common set of SQL commands that work across all databases, but there are many variations from one database to another. So again, for portability, I'm going to keep it simple. I'll call the executeQuery method, and I'll execute the SQL statement select asterisk from states.

States is the name of a database table that exists both in the MySQL database and the HyperSQL database that I'm working with. Now, to test the results, I'm going to find out how many rows are returned. In JDBC, there isn't a single property of the ResultSet object that you can look at. So instead, you move the cursor to the last row of the ResultSet and then find out what row number you're on. I'll use this code rs.last. The last method means move the cursor to the end of the ResultSet, and then I'll do a little bit of system output, and I'll output a string of number of rows, and I'll append to that the result of the method getRow, which looks like this, rs.getRow.

The getRow method returns an integer value, which represents the current row number. The JDBC ResultSet starts numbering its rows from one. So if I have a table of three rows, the getRow method would return one for the first row, two for the second, and three for the third. That's different than a Java array which starts counting at zero. And as long as you know the difference between the two, the numbering system for arrays versus the numbering system for databases, you'll be in good shape. I'll comment out the remaining System out Command, saying I'm connected, because now I'm interested in finding out how many rows of data I have.

So that's it. I'll save my changes, and I'll run the code. And I get back the message number of rows 50, and that's correct. There are 50 states and 50 rows in the states table in my database. I'll clean up my code, I'll delete unneeded comments and close up some extra white space, and then I'll test it one last time, and I'll see that I'm successfully connecting, that I'm getting back a scrollable ResultSet where I can move the cursor up down and back and forth as much as I need to, and I'm able to get the data back that I need.

Finally, I'll make sure that I have closed my resources. I'll return to my code, and I move down to my finally block where I am checking for the connection, making sure it's not null, and then closing it. Just like the Connection object, you need to explicitly close your Statement object and your ResultSet object. I'm going to copy this code and paste it in a couple of times. You should close objects in reverse order for how they were created. So the Connection was created first, then the Statement, and then the ResultSet, so I'm going to close them in reverse order.

I'll change my first if clause to rs, and if it's not null I'll close it, then I'll change the second block to the Statement, changing both the conditional logic and the call to the close method. All three of these interfaces have this close method, and again, it's up to you as the developer to make sure that you're closing these resources when you're done. If you forget to close a resource, with a file-based database you'll probably be fine, but with a network environment you might end up leaving a connection open to your database server, and that can cause problems at the server level later on.

Just make sure you have closed all of your resources when you're finished, and you'll be in great shape. Having made some more changes, I'll run the code one last time. I'm seeing I'm connecting and getting the data back, and so all this code is complete. And this can be used as a good model for how you execute any StaticSQL statement.

Show transcript

This video is part of

Image for Java Database Integration with JDBC
Java Database Integration with JDBC

32 video lessons · 6364 viewers

David Gassner
Author

 
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

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

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.


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.

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
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.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

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
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.