Start learning with our library of video tutorials taught by experts. Get started
Viewed by members. in countries. members currently watching.
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.
The first thing to learn in working with JDBC is how to connect to a database. I'm going to start with MySQL. To connect to MySQL, you'll need a Java driver, and you can get a free driver from mysql.com/downloads. On this screen, scroll down to the Connector section and look for Connector/J. You can get the most recent version of Connector/J from this website. But to make this very easy, I have included a copy of the driver in the free exercise files that accompany the course.
Go to the Free exercise files, to the libs folder, and locate them mysql jar file and copy it to the clipboard. Now go to Eclipse and open this project, ConnectMySQL from the exercise files. If you don't have access to the exercise files, create a new Java project, add this class to the package com.lynda.javatraining.db and type in the code that you see here. That creates three constants named USERNAME, PASSWORD, and CONN_STRING. Now I'm going to add the MySQL driver to my project.
I'll right-click on the project in the Package Explorer, and I'll create a new folder. You can name the Folder anything you like. I'm going to name it libs for libraries, then I'll Paste the jar file into the folder. Now, just because this jar file is a part of the project, doesn't make its code automatically available to the code in my application. I have to add the JAR file to the project's Build Path. To do that, I'll right-click on the JAR file, I'll choose Build Path > Add to Build Path. Later on I can configure the Build Path by right-clicking again, and once again going to Build Path, and this time selecting Configure Build Path, and that will take me to the Java Build Path Category of my Properties panel.
I have added the JAR file to the Build Path, and I should now be able to call its code. To connect to MySQL database, you need these three string values, the USERNAME, the PASSWORD, and the CONN_STRING or URL. The USERNAME and PASSWORD are determined by the users in your database. I created the USERNAME, dbuser, and assigned it this password in a previous video of this series, and if you don't have that user set up, you should set it up now. So I'm going to uncomment those two lines of code, and they're ready to use.
This last line of code creating the CONN_STRING has a format that's determined by the driver. The MySQL driver requires a CONN_STRING that starts with jdbc in lower case, then MySQL also in lowercase separated with colons. After MySQL, there's ://, then the DNS name or IP address of the host server. I'm working with MySQL on my local system, so the address of my server is localhost. But if I were working with a remote server, I might put in the IP address or that server's name.
Finally, the last part of the string is the name of the database I'm connecting to. So again, if you don't have access to the exercise files that accompany the course, you can create this code easily. Now I'll move the cursor to within the main method. In Java 6 and Java 7 you can jump directly to connecting to the database. But in previous versions of Java, you first have to load the driver class into memory, and you do this with code that looks like this, Class.forName, and then you pass in the fully qualified name of your driver class as a string.
The name of the MySQL driver is com.mysql.jdbc.Driver. If you type that code in, you'll see that a warning is displayed, and if you move the cursor over the Warning indicator you will see an Unhandled exception type of ClassNotFoundException. I'll click on the warning, and I'll add a throws declaration to the main method. So here's what this code is doing. Class.forName is used in Java to load a class dynamically. That is by loading its fully qualified name as a string.
It loads the class into memory, but it doesn't create an instance of the class, that is it doesn't instantiate it. Now in Java 6 and Java 7, you don't need this code, and I'm working in Java 7, so I am going to comment it out. Now the next step is to create an instance of a class called Connection. I'll type in the name of the class, and it's actually an interface, and I'll press Ctrl+Space. For MySQL, you'll see that there are two interfaces available, one in the packagejava.sql and one in com.mysql.jdbc.
You should always choose a version of an interface from java.sql. This will make your code more portable so you'll be able to take the same code that you wrote for MySQL and point it instead at another database like SQL Server. I'll select the Connection interface from java.sql, and that adds the import statement. Then I'll name the new object conn, and I'll assign it an initial value of null. The next step is to connect to the database. I'll type in conn =, and I'll call a method called DriverManager.getConnection.
I'll type in the name of the class, DriverManager, and press Ctrl+Space, and that adds an import statement for that class. After I have added the import statement, I'll type in a dot and press Ctrl+Space, and I'll see that there are three versions of the getConnection method. I'm going to use the third version of the method that looks for a url, a user, and a password. For the url ,I'll choose CONN_STRING, I'll set the user to the USERNAME, and the password to the PASSWORD. I'll complete the code, and I'll expand my editors so we can see all of it, and that's all the code that I need to connect to my database.
Now once again, I'm seeing the warning indicator, so I'll move the cursor over the warning indicator, and I'll see that I have an Unhandled exception type of SQLException. When you call to getConnection method if it succeeds everything will be fine, but if it fails in some way it will throw an exception, and you'll want to handle it explicitly. So I'll click on the warning indicator, and this time I'll surround the code with a try-catch block. Within the catch block which is catching SQLException, I'll delete the comment and the call to print stack trace, and then I'll add error output, I'll type in syserr, a code template and press Ctrl+Space, and I'll output the error to my error output.
The final step is to close the connection. For all JDBC resources, including connections, statements, and results sets, if you open them you have to close them. There are a few different ways of doing this, but I'm going to show you the most explicit approach here. I let a finally clause after the catch, and within a finally clause I'll first find out whether the connection object is null. I'll use if conn not equal to null, and if that condition is true, I will call conn.close.
Now once again, you will see that a warning is been generated I'll move the cursor over that warning, and I'll see that the call to the close method can also throw SQLException. Now you can write a whole bunch of complex code wrapping this if clause inside another try catch block, but a much simpler approach is to set your main method so that it throws SQLException. So I'll click on that warning indicator, and I'll Add the throws declaration, I'll go to the Throws Declaration, and because I commented out Class.forName, I no longer need to look for ClassNotFoundException, and that's my completed code.
Now to verify that I have connected correctly I'll move my cursor within the try block, after the call to make the connection, and I'll use system output and an output Connected. Later on I'll show you how to get a lot more information from the database, including retrieving data, but for now this will be adequate. I'll save my changes, and I'll run my application, and I get the message connected. Now to verify that this code works the way I expect, I'll make an intentional error. I'll change my PASSWORD from dbpassword to dbpassword123.
I'll save and run the code again, and this time I get an SQLException with a message of access denied. And so I know that my code is correctly structured, and I'm creating the connection if my credentials are correct. I'll change my code back so that it's correct, I'll test it again, and I'm connected and so now I know I'm ready to move on to the next step, which is retrieving data from my MySQL database.
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.