JDBC
08 Feb 2016JDBC (Java Database Connectivity) is a general purpose data access library baked into the Java development and runtime. This library’s purpose is to lower the level of complexity in connecting to different database vendors providing a consistent interface no matter what database you’re connecting to.
In today’s post, I’ll go through the basics of using this library. This blog post will be in context of connecting to a PostgreSQL database.
Drivers
JDBC is based on the premise of drivers. The driver code itself is what fills in the architecture with an implementation that your applications will use. To enumerate all of the drivers, currently in context of your application you can use the following:
I use the term “in context” because whilst you may have the required JAR installed on your system which will be a particular database vendor’s connection library for JDBC, you’ll need to make sure that it’s available on your class path.
For my example, I only have Postgres available to me:
The driver string that you saw in the section above plays an important role in establishing a connection to your database. Before you can start to work with Connection
, Statement
and ResultSet
objects you first need to load in your vendor’s library implementation.
This will reflect your driver into your application ready for use.
Making a connection
To establish a connection with a database, you’ll need to specify a connection string with all of the attributes required to direct your application to the database.
JDBC has a uniform format for specifying its connections with each vendor. Postgres conncetions are no different.
A connection is established using the DriverManager
class like so.
Running queries
Running retrieves on your database normally comprises of three processes:
- Preparing a statement to run
- Executing the statement
- Enumerating the results
The preparation of the statement is fairly straight forward. The createStatement
method on the Connection
object will allow you to create an empty statement, whereas prepareStatement
will allow you to provide some SQL directly.
A slightly more complex example where you’d pass in some parameters into your statement might look like this:
Enumerating a ResultSet
object can be achieved with a simple while
loop:
Cleaning up
Finally, all objects should be cleaned up afterwards by using the close
functions provided.
Other topics
This blog post is just enough to get up and running. There are plenty more complex topics inside of JDBC to be learned: