How to connect java with mariaDB localhost via unix soket?

Viewed 111

I'm a 2 year teacher of informatics and currently in my second year of teaching but I have little experience in connecting database to java. The school provides a localhost:3306 on its private server with these database specification:

enter image description here

I can connect a mysql community database from my PC without any problem but I don't know how to approach connecting to the unix socket.

How would i be able to connect the schools database server with a java program.

1 Answers

This can be done with the official MariaDB driver, which can be found here.

A simple example of this:

import java.sql.*;

public class MyConnector {

public static void connect(String dbLocation, String dbDriver, String user, String password) {
 
     Connection c = null;
     Statement st = null;

    try {

        Class.forName(dbDriver);
        // Connect the driver to your classpath
        c = DriverManager.getConnection(dbLocation, user, password);
        // Now java is connected to the database
        st = c.createStatement();
        
        String changeTable = """
            USE mytable;
            SELECT * FROM mytable WHERE id = 1;
        """;

        st.executeUpdate(changeTable);
        
    } catch (Exception e) {
        System.out.println("[FATAL] Error: " + e.getMessage());
    }


public static void main(String[] args) {
    
        String dbDriver = "org.mariadb.jdbc.Driver";
        String user = "root";
        String pass = "root";
        String dbLocation = "jdbc:mariadb://192.168.100.174/db";

    connect(dbLocation, dbDriver, user, root);
}
}
Related