Search code examples
javadatabasepostgresqlgradleconnection

How to instance 1 connection class for multiple requests?


So I'm currently working on a project that will be using a database but its my first time trying fiddling with it on java. But I'm already seeing my first problem is how would i make one single file that handles connection while other files handles GET/ADD/UPDATE/DELETE (one for each table) what would properly be the best way on doing this ? To not having to place connection values in each file and do the connection

I though about extending the connection class with the other classes but idk if its a great idea.

import java.sql.*;

public class DatabaseConnection {

    public static void main(String[] args) {
        final String url = "jdbc:postgresql://localhost:5432/Database";
        final String user = "dbuser";
        final String password = "dbpass";

        try(Connection conn = DriverManager.getConnection(url, user, password)) {
            System.out.println("Connection successful!");
        } catch (SQLException e) {
            System.out.println("Connection failure.");
            e.printStackTrace();
        }
    }
}

What would be the best approach?


Solution

  • Maybe i'm wrong, but i think you need connection pool. Try to find instruction here https://www.baeldung.com/java-connection-pooling