Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Connecting to multiple databases

From: Java Database Integration with JDBC

Video: Connecting to multiple databases

To make it easier to switch between databases. I'm going to re-factor the code that I have written so far, so I can easily switch from MySQL to HSQL by simply passing in a single argument to a method. My goal is to show that once you have a connection, the code you use to make a request to the database and process the results is almost exactly the same from one database platform to another. I'm working in a project called MultiConnect where I have versions of the Main class that I have already coded in other projects.

Connecting to multiple databases

To make it easier to switch between databases. I'm going to re-factor the code that I have written so far, so I can easily switch from MySQL to HSQL by simply passing in a single argument to a method. My goal is to show that once you have a connection, the code you use to make a request to the database and process the results is almost exactly the same from one database platform to another. I'm working in a project called MultiConnect where I have versions of the Main class that I have already coded in other projects.

I have one class that connects to MySQL, and I'll test that and make sure that it's working, and I have one that's connecting to HSQL, and I'll test that as well. Now, I have created a separate Utility class called DBUtil which only currently has some commented out code. I'm going to uncomment that code, and you'll see that there are four private strings, a username and a password, which will be usable on both databases because I have set it up so that the same user name, and the same password are available on both, and then two versions of my Connection string, one for HSQLDB and one for MySQL.

This class will have static methods that either return objects or processed results, and it's first job will be to have a static method that returns a particular kind of connection whatever kind of connection I request. I will place the cursor after the static final string declarations, and I'll declare a new public static method that returns an instance of the Connection interface. As I have done in other classes, I'll be sure to include the import statement for the Connection interface from java.sql. I'll name the static method getConnection.

Now, in order for my application to be able to request the type of database it wants to talk to, I'm going to create an enumeration, a set of possible values, and they will match the two types of databases. I will go to my package again, and I'll right-click and select New > Enum. I'll name my enumerator DBType. I'll create it, and then within the enum declaration, I'll type in constants representing each of the two databases, HSQLDB and MySQL, and that's all I need.

The entire purpose of this enumerator is to guarantee that I'm requesting a database that I know exists. I'll save those changes and return to my Utility class. Now when getConnection is called, I require that the database type be passed in, so I'll add an argument. Its data type will be DBType, the name of the enum I just created, and its name will be dbType with a lowercase D-B. I'll expand the editor to full screen, and now within the call to the method, I'm going to inspect that arguments value and find out which type of database I'm supposed to connect to.

I'll add a switch statement. I'll type in switch and press Ctrl+Space, and choose the switch case structure, and for the Key I will look at dbType, the argument that was passed in. The first case I'll inspect will be MySQL, the type from the enum class, and then before I fill in the code for this case I'm going to duplicate it. I'll select these three lines and do a duplication, and I'll change the case statement for the second case, for MySQL to HSQLDB. Now I'm ready to make and return my Connection object.

For MySQL, I'll use a return statement, and I'll call a driver manager, making sure, again, to add the import statement, then I'll call the getConnection method. Once again, as I have previously, I'll use the three arguments version of the getConnection method, and for MySQL I'll pass in the Connection string M_CONN_STRING, and then the USERNAME and the PASSWORD. I'm not going to need my Break command here because I'm immediately returning the Connection object. Now I'll copy that code and paste it into the next case, I'll once again delete the break statement that I don't need, and I'll go to the second call and change the Connection string from M to H. And for the default, I'll return null.

You'll see that there are warnings being displayed in Eclipse, I'll move the cursor, and I'll see that I have an unhandled exception of SQL exception. To keep this simple, I'm just going to add a throws declaration to my method signature. I'll click the warning and choose Add throws declaration. I save the change, and now my DBUtil class is complete. Its entire purpose is to receive a type and return a connection object. Now I'll put this utility class to use. I'll go back to the Package Explorer.

And I'm going to use this class, ConnectHSQL. I'm going to duplicate this class, I'll copy and paste, and I'll name the new copy Main, and this will be my new Main class for my application. I'm going to close all the other tabs and expand the editor for this new class. Now for this version of the class I no longer need to store the Username, Password, and Connection string in the Main class, that's all being handled now by the database utility. So I'll delete those lines of code, then I'll go down to the try block where I'm getting the Connection, and I'm going to comment out that call.

So I'm no longer getting the Connection directly from the driver manager, and I'll replace it with this code, conn = DBUtil, my new utility class, and I'll call getConnection, and I'll pass in the type of database I want from the enum class. I'll start with HSQLDB, and so now I'm making a connection to the HSQL database and getting data back. I'll save my changes, and I'll run the code, and I get back 50 rows from the states table that seems to be working. I'll clear the console, and I'll come back to my call to getConnection, and I'll replace it with MySQL.

I have saved my changes and run the code again, and once again, I get back 50 rows because these two databases have exactly the same number of rows in the states table and, in fact, the exact same data. So now I have a re-factored application where I have moved all of the logic for how I get a connection to my database into Utility class, and I have also hidden the Username and Password and the Connection strings. Now as I start building out my application, I have a single place in my application to go to get a connection.

And if I need to change the way I'm getting my credentials or how I'm connecting to the database, I have a single set of code to maintain.

Show transcript

This video is part of

Image for Java Database Integration with JDBC
Java Database Integration with JDBC

32 video lessons · 6371 viewers

David Gassner
Author

 
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

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
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.


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.

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

Your file was successfully uploaded.

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.