
DriverManager vs. DataSource
At a high level, there are two ways to connect to a SQL database in Java.
- DriverManager
- DataSource
When using DriverManager, you place the database driver JAR (such as mysql.jar) in each apps /WEB-INF/lib folder and then you configure Eclipse to use the JAR. When using DataSource, you place the database driver JAR on the system running the application server, which would be Liberty in this example.
DataSource has numerous advantages over DriverManager. With DataSource you only need to place the JAR on one system (the Liberty application server). Another advantage is that you can leverage additional capabilities, such as connection pooling. This article describes how to configure Liberty for connections via DataSource. Refer to this article to connect to a database via DriverManager.
In ths example, the MySQL JDBC driver is downloaded from https://dev.mysql.com/downloads/connector/j/. This will download a tar archive. Move the tar archive onto your Liberty server (Linux in this example). Decompressed the gzip compress tar archive.
~]# gunzip mysql-<version>.tar.gz
Extract the tar archive.
~]# tar -xf mysql-<version>.tar
Copy the MySQL JAR into a directory where you will be storing your JDBC drivers (/opt/jdbc in this example).
~]# cp mysql-connector-java-version-bin.jar /opt/jdbc
Configure your Liberty server to use JDBC by adding the jdbc-<version> feature to your your ${liberty_install_root}/usr/servers/your_server/server.xml file.
<featureManager>
<feature>servlet-4.0</feature>
<feature>jdbc-4.0</feature>
</featureManager>
Restart your Liberty application server and validate that your ${liberty_install_root}/usr/servers/your_server/logs/console.log has the following event.
[AUDIT] CWWKF0012I: The server installed the following features: [jdbc-4.0]
[AUDIT] CWWKF0012I: The server installed the following features: [servlet-4.0]
Create the database and library in your server.xml file. This is an example of the markup you would use for a mySQL database.
<dataSource id="mySQL" jndiName="jdbc/mysql">
<jdbcDriver libraryRef="mySQLlibrary"/>
<properties serverName="example.com" portNumber="3306" databaseName="example" user="john" password="secret"/>
</dataSource>
<library id="mySQLlibrary">
<fileset name="${liberty_install_root}/usr/shared/resources/mysql/mysql-connector-java-8.0.11.jar"/>
</library>
You should now be able to configure your Java application to connect to the database. For example, this article describes how to connect to the database in Java using Eclipse.
Did you find this article helpful?
If so, consider buying me a coffee over at