Connecting to a Database – Step by Step

The database driver

This example shows the different steps needed to connect to a database.
In the example the Microsoft SQL Server is used, but the steps applies to all types of database engines.
The first thing you need to do is to consider what driver to use. There are different types of drivers
(the different types is not covered here) and the most efficient and widely used driver is a Type 4 driver.
A Type 4 driver is completely written in Java and is not dependent on any native code. Each database engine has its own driver
so you can only use a driver for that particular database engine.

Now, to make the driver available to the JVM you need to load the class:

For the JVM to be able to find that class, you need to make sure the class is on your classpath.
Usually the class is located within a .jar-file that can be downloaded from the database vendor.

Creating the database connection

To create the connection you use the static method getConnection() of the java.sql.DriverManager class.
The method has several overloaded variants, and one of them takes a url, userid and password as arguments.
The database url slightly differs from one type of database to another. For Microsoft SQL Server it looks like this:

Create the Statement object and executing a query

Now that we have established a connection, we want to create a Statement object and execute a sql query.

Now we have retrieved the data from the table called ‘table’ into a ResultSet and all we have to do now is loop through it.
Assume the table has two columns, id of type int, and value of type varchar:

Cleaning up resources

Now all we have to do is close the connection. Actually we should close all the instances of Connection, Statement and ResultSet and
it’s done in reverse order from which they were created:

For many of the code statements above it is required to handle an SQLException in case anything goes wrong.
Thus you’ll have to enclose much of the code in a try / catch block which was excluded in the example to make it more readable.

Search for more Java info on this site here:
Custom Search

Please type any questions here.