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

Java Database Integration with JDBC

Connecting to a MySQL database server


From:

Java Database Integration with JDBC

with David Gassner

Video: Connecting to a MySQL database server

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

Connecting to a MySQL database server

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.

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