Adding a JDBC driver for your database

Connecting to an RDBMS from a Java application is done through a JDBC driver. Most (if not all) database vendors include JDBC drivers for their RDBMS. A JDBC driver, in practice, is just a Java dependency (a JAR) in your project. If, for example, you need to connect your application to a PostgreSQL database, you will need to add the postgresql-x.x.x.jar file to your classpath. This, of course, can also be done with Maven. It's through this JDBC driver that your Java application communicates with the RDBMS, and it does so by establishing connections and executing SQL statements to retrieve data.

We are not covering the details about RDBMS and SQL in this book. These topics are complex enough by themselves to deserve a complete book about them. There are plenty of good bibliographic and online resources you can consult to learn more about these topics.

In this book, we are going to use an H2 database. H2 is a popular open source database engine that doesn't require you to install anything on your computer. All the concepts apply to other RDBMS as well, and we'll include snippets or commented sections in the accompanying code that show the specifics for MySQL and PostgreSQL, in case you want to experiment with these databases by yourself.

Adding a JDBC driver is as simple as including the right dependency in your project. For example, to include the H2 JDBC driver, add the following dependency to your pom.xml file:

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.196</version>
</dependency>

Or if you want to use MySQL or PostgreSQL, add the following dependencies:

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.1.4</version>
</dependency>
JDBC was designed to support not only relational databases, but also any kind of data source, including file systems or object-oriented systems. Keep this in mind when you need to connect your application to any kind of data source; there might be a JDBC driver for it.

You can, of course, include several JDBC drivers in the same project. The chapter-05 application includes all of the previous drivers.

In old versions of JDBC, you had to manually load the JDBC driver class using the Class.forName method. This is no longer required in JDBC 4.0. Any JDBC 4.0 driver in the classpath is automatically loaded.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset