Just Show Me the Code!
Here’s a TL;DR section for you. Add the JDBC Driver (check the latest version, and check what’s new in version 3.0):<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>LATEST</version>
</dependency>
Open the connection (alternatively use a try-catch block to close the connection automatically):
Connection connection = DriverManager.getConnection(
"jdbc:mariadb://localhost:3306/database_name",
"user", "password"
);
If you are using SkySQL, use the following connection string:
jdbc:mariadb://example.skysql.net:5001/jdbc_demo?useSsl=true&serverSslCert=/path/to/skysql_chain.pemClose the connection (if not using a try-catch block):
connection.close();Create (
INSERT), update (UPDATE), and delete (DELETE):
try (PreparedStatement statement = connection.prepareStatement("""
INSERT INTO table_name(column1, column2)
VALUES (?, ?)
""")) {
statement.setString(1, someString);
statement.setInt(2, someInteger);
int rowsInserted = statement.executeUpdate();
}
Read (SELECT):
try (PreparedStatement statement = connection.prepareStatement("""
SELECT column1, column2
FROM table_name
""")) {
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
String val1 = resultSet.getString(1); // by column index
int val2 = resultSet.getInt("column2"); // by column name
// ... use val1 and val2 ...
}
}
If you want more detailed information, keep reading…
Connecting to MariaDB from Java
JDBC is the foundational technology for connecting Java applications with SQL databases. Persistence frameworks such as JPA/Hibernate, MyBatis, and jOOQ use JDBC under the hood, so understanding the key concepts in JDBC will put you in a good position to explore these persistence frameworks. When you want to connect to a database from Java, you need aConnection object. I wrote a tutorial that explains how to get one of these objects through a JDBC driver (you’ll learn what a JDBC driver is as well):
- JDBC Tutorial Part 1: Connecting to a Database (DZone | Hacker Noon | DEV)
Here’s the video version of the tutorial:
Source code: https://github.com/mariadb-developers/java-quickstart/tree/main/jdbc/part1Executing SQL Queries from Java
With a connection established, you can run SQL statements (queries or updates) using aPreparedStatement object. This tutorial explains how to do so in a safe way to avoid SQL injection attacks:
- JDBC Tutorial Part 2: Running SQL Queries (DZone | Hacker Noon | DEV)
Using Database Connection Pools
When you implement a web application, web service, or any other kind of application that allows multiple clients and connects to a database, you should use a connection pool. This tutorial explains what a connection pool is and how to use it:- JDBC Tutorial Part 3: Using database connection pools (DZone | Hacker Noon | DEV)
