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

Using a persistent database connection


From:

Java Database Integration with JDBC

with David Gassner

Video: Using a persistent database connection

If you have been working through the exercises in this video series, you might have noticed that we're opening a lot of database connections. I'm working in a version of my project called ConnectionManager that has the code for updating a database table. And I'll go to the tables package and open AdminManager.java. The way this application is currently architected every time I call my DBUtil class's getConnection method, I'm opening a new connection, and then I am closing that connection when that method is finished. And if you count up all the times that we are using the get connection method, you'll see that we're opening and closing connections many, many times.
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

Using a persistent database connection

If you have been working through the exercises in this video series, you might have noticed that we're opening a lot of database connections. I'm working in a version of my project called ConnectionManager that has the code for updating a database table. And I'll go to the tables package and open AdminManager.java. The way this application is currently architected every time I call my DBUtil class's getConnection method, I'm opening a new connection, and then I am closing that connection when that method is finished. And if you count up all the times that we are using the get connection method, you'll see that we're opening and closing connections many, many times.

In JDBC this is into great practice, and that's because connections are expensive. They take time, memory, and resources, and so to the extent possible you should minimize the opening and closing of connections by reusing connections. When you work in a Java Enterprise Edition Server environment such as JBoss, the server typically will provide connection pooling. It's a multi-user environment, and so it's vital that multiple users reuse those connections. If you're building your own Java application, though, either as a console application like this or a desktop application, you might need to write your own logic.

In this project, I have provided a bit of code called the ConnectionManager. The ConnectionManager class is a singleton, a class that can only be instantiated once. This is a common design pattern in Java, and it's used whenever you want to make sure that your entire application is using the same object. The ConnectionManager starts with a private static instance of itself, and the name of that field is simply instance. It's initially set to null. It then contains String fields for all the credentials we'll need to connect to databases and a DB type field which is not static.

So it can be changed after this class is instantiated. There is a private field for the connection object, and there's only one, and it's initially set to null. Now here is the code that manages the singleton aspect of the class. The goal of a singleton is to make sure that the entire application can get a reference to it, but it can only be instantiated once from within the class itself. And so we control that with a private constructor. When you mark the one and only constructor method as private, that means that it can only be constructed from within this class.

And then there is a static method called getInstance which checks to see whether the one instance is null, and if it isn't, it instantiates it, and then either way, it returns it. So to get a reference to the one and only ConnectionManager object for the whole application, other parts of the application will call the static method ConnectionManager.getInstance. Let's take look at the rest of the code. There is a public method called setDBType that lets the application decide what type of database we're going to use either MySQL or HSQLDB.

There is a private method called openConnection. We'll only call this method if the connection isn't already open, but it looks exactly the same as it did in our DBUtill class. It checks the database type and then uses the appropriate logic to open either MySQL or HSQLDB. There is public method named getConnection. This method will be called from the one and only instance of the ConnectionManager. It checks to see whether the one and only connection is null, and if it is it opens it and then it returns the reference.

And if the code gets all the way down to this line, it returns the already open reference. Finally, there's a close method. Remember that you should always explicitly close your connections, and using a singleton manager makes no difference. So now the singleton manager is responsible for closing the connection. And in this case, it both closes it and sent it to null so that we can explicitly manage the opening and closing of the connection from anywhere in the application, but only by calling this method. This code is fairly intensive, and if you don't have access to the exercise files, I don't want to make you type it out.

So I have provided this project in the code section of the free exercise files. Now let's see how we can use the ConnectionManager class. I'll go to my main class. The first thing I'll do is set the database type, either HSQLDB or MySQL. I'll place the cursor after the comment. Now I'll get a reference to the ConnectionManager object and set the database type. I'll say ConnectionManager.getInstance, and that gives me the reference to the ConnectionManager, and from there I'll set the database type with DBType.MYSQL.

I'll also add code at the end of the method to ensure that the connection has been closed, and that'll look like this ConnectionManager.getInstance().close. So that's all I have to do from the main class, I set the database type and make sure the connection is closed. Now let's go to the AdminManager class. The AdminManager class is where we have all these calls to the getConnection method, and we're opening and closing the connection over and over. I'm going to change the model for this. I'm going to create my connection as a static field of the AdminManager class.

I'll place the cursor inside the class declaration, but before any of the methods, and I'll declare a private static Connection, and I'll name it conn, as it's been named previously. And I'll get its reference by calling ConnectionManager.getInstance().getConnection. So now the first time any of these static methods are called, this static connection object will get its reference automatically. And I can go through all the rest of the code, and I can comment out or delete all of the other code that's getting the referenced from the DBUtil class.

I'll delete it from the getRow method, I'll keep on scrolling down, and I'll delete it from the Insert method, and also from the Update method. I'll save my changes, and I'll go back to my main class, and I'll run the code again. And because I have system output scattered throughout the application, I'm able to see the order in which things are happening. First, I get the message that the application is starting then the message that the connection is opened. Now, notice I still have input that I have to provide, and if things are working, the connection is still open.

So I went to the number one and a new password, and I get back the message Success. And then I see the message that the connection is being closed, because I get to the code in the main method that calls the close method of the ConnectionManager. So, now I'm using a single connection to my database. I'm saving memory, time, and resources. Again, if you're working in a Java Enterprise Edition Server environment, you'll have a connection pooling architecture that the server provides. But if you're working on a Console or a desktop application, it's up to you to write this code, and this is one possible model that you can try out.

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.