Ready to watch this entire course?
Become a member and get unlimited access to the entire skills library of over 4,900 courses, including more Developer and personalized recommendations.Start Your Free Trial Now
- View Offline
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.
- 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
Skill Level Intermediate
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.