New Feature: Playlist Center! Pick a topic and let our playlists guide the way.

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

Java Database Integration with JDBC
Illustration by Don Barnett

Handling JDBC exceptions


From:

Java Database Integration with JDBC

with David Gassner

Video: Handling JDBC exceptions

Just as with all Java programming, when something goes wrong in JDBC, you'll get an exception. In JDBC, most methods of JDBC objects throw a class called SQLException. SQLException is extended from the Exception class, and it inherits all of the tools that are a part of that class, such as getMessage and getLocalizedMessage, string representations of an error message, getStackTrace, and many other tools. But JDBC is all about databases, and so its special exception class SQLException is specifically designed to give you information about what's going on in the database.
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

Handling JDBC exceptions

Just as with all Java programming, when something goes wrong in JDBC, you'll get an exception. In JDBC, most methods of JDBC objects throw a class called SQLException. SQLException is extended from the Exception class, and it inherits all of the tools that are a part of that class, such as getMessage and getLocalizedMessage, string representations of an error message, getStackTrace, and many other tools. But JDBC is all about databases, and so its special exception class SQLException is specifically designed to give you information about what's going on in the database.

SQLException adds these methods, getErrorCode returns an integer value which tells you what might have gone wrong. The Error code is unique to the particular database, so a numeric error code for MySQL won't be the same as for HSQLDB, and so on. And there's also a method called getSQLState which returns a five-character string. It's just like the error code. It's specific to the particular vendor and the particular database, but it's a string instead of an integer. To find out what these values mean, you'll need to look at the documentation for your particular database, MySQL, HyperSQL, SQL Server Oracle, and so on.

I'm going to be showing you how to look at the Exception object and get these values out, but you'll need to look at the documentation to find out what they mean. There are also methods called getNextException, setNextException, and iterator. When something goes wrong at the database level, many times it'll be a cascading set of exceptions, and these methods let you deal with those stacks of Exception information. Let's take a look at some code. I'm working in a project called JDBCExceptions, which is just like the projects that I have created previously in this video series.

It has the Utility class that lets me choose which database I want to work with, HSQLDB or MySQL, and then it executes a single statement and brings back a result. Before I run this code, I'm going to modify the SQL statement. So I'm more specific about the names of the columns that I'm getting from the database. I'll get rid of the asterisk and replace it with stateId and stateName, separated with a comma. These are the names of the actual columns in my states table in both databases.

I'll test the code and make sure that I have got it correct. I'm working with HSQLDB first, and I get back to my data, and then I'll change from HSQL to MySQL, and I'll run the code again, and I see that it works there too. So now I'm ready to introduce an intentional error. I'll start by getting the structure of my database wrong. Instead of states, I'll look for data from a nonexistent table named state. I'll run the application, and I get back an error object. Notice that this error object is specific to MySQL.

It has a pretty lengthy name, but it has the message Table 'explorecalifornia.state' doesn't exist. Now let's throw the same error for HSQL. I'll change my database type and run the code, and this time I get back a different error object, and it means the same thing, but the message is different, user lacks privilege or object not found. Now, to get more information out of this Exception object, I'm going to add some more detailed exception handling. I'll go to my Database Utility class, DBUtil, and I'm going to add a new method that I'll call processException.

I'll use the keywords public, static, and void, I'll name the new method processException, and I'll have it receive a single argument data typed as SQLException, and I'll name the object simply e. For now my only goal is to output the detailed information about the exception. So I'm going to add three error output lines. I'll use the System.err code template, I'll expand it, and then I'll duplicate it a couple of times. For the first line I'll output the error message. I start with a label Error message, and then I'll call e.getMessage.

Now this line of code would be the same regardless of what kind of Java exception I get. But now I'm going to process the methods that are unique to SQLException. I'll move the cursor to the second line, and this time the label will be Error code, and I'll append to that e.getErrorCode. And finally, I'll output the SQL state the string representation of the error. I'll save my changes to the DBUtil class, I'll go back to my Main class, and now within the catch block instead of outputting the error object in its raw form, I'll use my new utility method, DBUtil.processException, and I'll pass in the Exception object.

I'll run the code now, and I see my error message, my code, and MySQL state. So my goal here is to start showing you some of the differences between databases. I'm currently working with HSQLDB, notice the Error code and the SQL state -5501 and SQL state of 42501. I'm going to spell my table correctly, but now I'm going to misspell a column name. I save the changes and run the code, and I get back exactly the same Error code and SQL state that I did before.

So for HSQLDB, misidentifying a column or table returns the same exception. Now let's switch back to MySQL. I'll change my database type, I'll leave the code that's misidentifying the column name, I'll run the application, and this time I get back a different Error code and a different SQL state. That's expected because now I'm working with another database, and notice the SQL state is 42S22. Let's remember that. I'll go back to the code, I'll fix the column name so it's correct, and now I'll get the table name wrong.

I'll run the code again, and I get a different Error code and a different SQL state, 42S02. Now let's explore some other errors. One of the most common errors is a user authentication error. I'll fix my column names and my table name. I'll go back to my DBUtil class where I'm storing my user credentials, and this time I'll get my username wrong. I'm working with MySQL, and I get an Error code of 1045 and an SQL state of 28,000. Now let's switch to HSQLDB, and I get back another Error code and SQL state, -4001 for the Error code and 28501 for the SQL state.

What I'm trying to get across here is that the Error codes and SQL states are going to differ both from one database to another but also in their patterns within a database. One database like HSQL might use the same SQL state for two different but similar conditions, whereas another database might have distinct SQL states and distinct Error codes. The only way you'll know what these codes mean--as I have mentioned previously--is to look at the documentation for your particular database management system, but once you know what these error codes and SQL states mean, you'll be able to write more detailed and more useful exception handling logic in your own application.

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

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

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.