Start learning with our library of video tutorials taught by experts. Get started
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.
When data is returned from the database server, it's encapsulated within the ResultSet object. The ResultSet has a cursor and in-memory pointer that goes from row to row. When the ResultSet is first returned, the starting cursor position is before the first row of data, that is, it's not pointing to any data at first. You have to explicitly move the cursor to the data in order to read it. The cursor can either be before the first row of data, on a row of data, or after the last row of data.
All ResultSets give you the ability to move the cursor forward, so the cursor starts before the first row, and the first thing you need to do is move it to the first row. If you're working with a scrollable ResultSet, you can explicitly move to a particular row, but if you're working with what's called a forward only ResultSet, that is a result set where the cursor can only move forward, then you move the cursor one row at a time by calling a method called Next. The Next method returns a Boolean value. When you call it, if it succeeds in moving the cursor to a row that has data, it returns true, and if it moves toward the row that doesn't have any data that would be after the last row, then it returns false.
And so, when working with a forward only cursor, the most common approach is to use a while loop. Within the conditional block for the while loop, you call the Next method. And if it returns true, you know you're on a row that has data, and you process the data. And if it returns false, then you know you have gone passed the available data, and you can exit the while loop and continue executing your program. Within the while loop, while the cursor is on a row with data, you call various methods to retrieve the data. If a particular column has string values, you can call a method called getString.
You can pass in either the name of the column as a string if you know it or the position of the column as an integer and the position start numbering at one. So let's take a look at some code. I'm working in a project called LoopingRows. In this project, Main method, I'm executing a query to retrieve all data from a table named Tours. Let's take a look at the structure of the Tours table. The Tours table has a number of columns. There is a primary key called tourId, a foreign key called packageId, a number of string columns, including tourName, blurb, description, and so on.
A double-column called price, an integer column called length, and many others. I'm going to write some code that assumes that we're getting back a record set based on the structure of this table, and it's going to loop through the rows that are returned and output some content for each row. I will go to Eclipse. Now I'm not going to put all of this output code in the Main method. Instead, I'm going to create a Utility class that I can call from anywhere in my application. I'll go to my DBPackage, and I'm going to create a sub package.
I'll right-click and choose New > Package, and I'll name my new package Tables. This new package eventually would contain one class for each table in my database. So I have created a new package, and now I'll create a new class for that table. I'll right-click and choose New > Class, and I'll name my class the same as the table, Tours. This is going to be Utility class. It won't be the start up class of my application, so I won't include a Main method, and I'll click Finish. Now I'm going to create static methods to process data. Within the class, I'll create a new public static void method, so I'll put in those keywords, and I'll call my method displayData.
I'll set this method up to receive a single argument, data typed as a JDBC ResultSet. I'll type in ResultSet, press Ctrl+Space, and choose ResultSet from java.sql, I'll name this argument rs, and I'll create the code block. Now, for the purpose of this exercise, I'm going to assume that the cursor is starting before the first row. I could add some additional code to make sure of that, but for the way I'm going to use this code in this application, I'm going to know where the cursor is. So I'm going to start with a while loop. I'll type in while, and I'll choose a while loop with a condition.
For the condition, I'll make it call to rs.next. So now as long as there's available data, I'll just keep on looping. I'm going to collect data from a number of columns and append it altogether to create a string for display. For this purpose I'll use a string buffer, I'll name this object simply buffer. And I'll instantiate it with the class's constructor. I'll expand my editor to full screen so I can see everything I'm typing. Now I'm going to get the current row number and append that as the tour number.
I'll use buffer.append, and I'll first add in a label of the Tour space then I'll append to that the value of rs.getRow. Now this is not a static value. The number will be whatever is first in this record set, and so if you re-sort the data, in some way these values won't stick with the data. If you prefer, you could instead call getInt and pass in either the name or the column index of the column containing the primary key value. So for example, I could instead pass in getInt("tourId").
So, after I have appended the primary key value, I'll then append a colon and a space. Now before we add more content, let's see how we're doing. I'll add some system output, and I'll output the value of buffer.toString. Notice that there are some warning icons when you call the next method or any of the methods that get data from the record set you might be throwing an SQLException. So I'm going to mark this method with the throws declaration, and indicate that it might throw that exception. I'll save my changes, and I'll go back to the main method.
I'll place the cursor within the try block, and within the try block, I'll call this new static method that I have just created. I'll type in the name of my new class, and I press Ctrl+Space to make sure I have imported the class, and then I'll call the display data method and pass in the ResultSet. I'll save my changes and run the code, and I see that I'm correctly getting back 26 rows of data. So now I'm ready to fill in the rest of my display method. I'll go back to my Utility class, and I'll add some more code. After I have gotten the primary key, the next step will be to output the tour name.
So I'll place the cursor after the call to the append method, and I'll append again. And this time I'll output the value of rs.getString, and I'll pass in the name of the column I'm interested in, tourName. Now the column names are not case-sensitive, and that's true for almost every database you might work with. It's certainly true with the MySQL and HSQLDB. So even though HSQLDB marks these column names as all uppercase and MySQL maintains the column names however you typed them in, you can type them however you like here in your Java code.
Next, I'll get the price of the tour. I'll create a new double variable that I'll name Price, and I'll get its value from rs, and this time I'll call the method getDouble, and I'll pass in the name of the column price. Before I output it, I'd like to format it, so I'll use an instance of the NumberFormat class, I'll type in the name of the class, and import it from java.txt, and I'll name the object nf for NumberFormat, and I'll get its reference by calling the static method, NumberFormat.getCurrencyInstance.
Notice that there are many methods that I could call from the NumberFormat class. This one's going to format the price as a dollar value. Then I'll format the price, I'll create a string called formattedPrice, and I'll get its value from calling the format method of the NumberFormat object with nf.format, and I'll pass in the price. And finally, I'll append that result to the buffer, using buffer.append, and I'll pass in a space and in an opening parenthesis, and then the formattedPrice, and then a closing parenthesis.
I already have my code to output the buffer's value. So I'll save my changes, I'll go back to the main method, and I'll run the code again, and there is the result. I'm looping through the data that's returned from the database, and I'm outputting information from the rows one at a time. When I finished with the last row, the next time I call the next method, it returns false because there is no more data, and I exit the loop, and I'm done. So that's the most classic way of working with data returned from the database. The cursor starts before the first row, you call the Next method and each time it returns true you're on the next row of data.
And you use the various get methods of the ResultSet to get a value from a column and process it in some way.
There are currently no FAQs about Java Database Integration with JDBC.
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
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.