How to connect a Java app with an SQL database?
Connect a Java application using JDBC
On this post, I will show you how to connect a Maven project with MySQL, I will be using the following:
- Java 18.0.2
- Maven 3.8.6
- MySQL 8.0.31
1. Create the database and add some records
First, we will execute the code below to create the database "dbexample" with a table named "person".
CREATE DATABASE dbexample;
USE dbexample;
CREATE TABLE person
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);
Once the table is created we will INSERT a couple of records on it.
INSERT INTO person (name) VALUES ('Edgar');
INSERT INTO person (name) VALUES ('Eduardo');
If we did everything right, we will get something like this after running a SELECT instruction.
SELECT * FROM person;
2. Setup the Maven project
We will use Maven to manage our dependencies.
You can google how to create a Maven project with your IDE. As a reference, in Eclipse you can create one going to "File > New > Maven Project".
We need to add the following dependencies to our pom.xml
file.
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
</dependencies>
NOTE: Remember to update your project everytime that you change your project dependencies. You can do it running the command mvn install
.
3. Connect our Java application with MySQL
We will use JDBC (Java Database Connectivity) to achieve this.
We need to define our connection url with the following structure:
jdbc:<RDBMS>://localhost:<PORT_NUMBER>/<DB_NAME>?serverTimezone=<TIMEZONE>
- RDBMS: The database system that you're using, i.e.
mysql
,sqlserver
. - PORT_NUMBER: The port configured by your database system, by default MySQL uses the port
3306
- DB_NAME: The database name that you defined on step 1.
- TIMEZONE: The server timezone.
Mine looks like this:
String connectionUrl = "jdbc:mysql://localhost:3306/dbexample?serverTimezone=UTC";
Next, we will create a Connection object using our connection url, user and password:
Connection conn = DriverManager.getConnection(connectionUrl, "root", "root");
At this point, the connection should be established and now we can execute a query.
PreparedStatement statement = conn.prepareStatement("SELECT * FROM person");
ResultSet results = statement.executeQuery();
Lastly, we show the results in the console.
while (results.next()) {
long id = results.getLong("id");
String name = results.getString("name");
System.out.println("id: " + id + " name: " + "'" + name + "'");
}
Since the connections to databases are prone to throw exceptions we need to wrap these instructions in a try...catch
block. The final code looks like this:
public static void main(String[] args) {
String connectionUrl = "jdbc:mysql://localhost:3306/dbexample?serverTimezone=UTC";
try (
//Create the connection object
Connection conn = DriverManager.getConnection(connectionUrl, "root", "root");
//Execute a SELECT instruction
PreparedStatement statement = conn.prepareStatement("SELECT * FROM person");
ResultSet results = statement.executeQuery(); ) {
//Show the results
while (results.next()) {
long id = results.getLong("id");
String name = results.getString("name");
System.out.println("id: " + id + " name: " + "'" + name + "'");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
4. Results
Now, if we run our application, we should get the 2 records that we inserted in our table.
โฌ๏ธ Download
All my projects are available on my GitHub profile, feel free to download them!
๐ฌ Comments
If you have any recommendation feel free to comment it. I appreciate any feedback!
๐ References
List of resources that I consulted and that may be helpful to go deeper on this topic.