Java Tutorial 87 – JDBC 4/7 Connecting to a MariaDB Database



Java Tutorial 87 – JDBC 4/7 Connecting to a MariaDB Database

Java Tutorial 87 - JDBC 4/7 Connecting to a MariaDB Database

In this tutorial, I will show you how to develop database applications using SQL and Java for MariaDB instead of MySQL in the NetBeans IDE.

1. Loading drivers

// Statement to load a driver:
Class.forName(“JDBC Driver Class”);

A driver is a class. For example:

Database JDBC Driver Class
MySQL com.mysql.cj.jdbc.Driver // JDBC 8.x
MySQL com.mysql.jdbc.Driver // JDBC 5.x
MariaDB org.mariadb.jdbc.Driver

2. Establishing connections

// Establish a connection
Connection connection = DriverManager.getConnection(databaseURL);
 
Database URL Pattern
MySQL jdbc:mysql://hostname:port#/dbname
MariaDB jdbc:mariadb://localhost:oirt#/dbname

Examples

For MySQL:
Connection conn = DriverManager.getConnection
(“jdbc:mysql://localhost:3306/test”, “user1”, “pass1”);

-You must configure either the server or JDBC driver (via the ‘serverTimezone’ configuration property) to use a more specific time zone value if you want to utilize time zone support. e.g., jdbc:mysql://localhost:3306/test?serverTimezone=UTC.

 For MariaDB
Connection conn = DriverManager.getConnection
(“jdbc:mariadb://localhost:3306/test”, “user1”, “pass1”);

– You don’t have to configure the server time zone for MariaDB.

3. Creating and executing statements

// Create a statement
 Statement stmt = conn.createStatement();

// Execute statement (for CREATE, DROP, UPDATE, DELETE or INSERT):
 statement.executeUpdate(“CREATE TABLE employee ( no VARCHAR(6) NOT NULL, name VARCHAR(25) NOT NULL, age INT NOT NULL, gender CHAR(1) NOT NULL);

4. Processing ResultSet

Executing statement (for SELECT):
// Select the columns from the Student table
ResultSet rs = statement.executeQuery
(“SELECT * FROM employee “);

Processing ResultSet (for select):
// Iterate through the result and print the student names
while (rs.next()){
System.out.println(resultSet.getString(1) + “t” + resultSet.getString(2) + “t” + resultSet.getInt(3) + resultSet.getString(4) + “t” + resultSet.getString(5));
}

// Iterate through the result and print the student names
while (rs.next()){
System.out.println(resultSet.getString(no) + ” ” + resultSet.getString(name) + ” ” + resultSet.getInt(age) + ” ” + resultSet.getString(gender) + ” ” + resultSet.getString(address));
}

5. Closing the connection

// Close the connection
conn.close();

Comments are closed.