Skip to content

Database

n-tdi edited this page Feb 21, 2023 · 2 revisions

Creating a Database object

For reference, everything is being created in the main method for simplicity sake, but it is up to you to structure your project any way you may like!

Main.java

public class Main {
    public static void main(String[] args) {
        String host = "localhost";
        int port = 5432;
        String username = "root";
        String password = "root";

        Database database = new Database(host, port, username, password);
    }
}

The Database class requires the host of your Postgresql server, the port that your Postgresql server is running on, and the log in credentials. you probably shouldn't put your username and password in a plain string, rather using a .env

Creating the Database object is super simple! Yet, we aren't done. In order to actually use our database in other Objects, we need to connect to it.

Connecting to a Database object

Actually connecting to a Database object is super easy.

Main.java

public class Main {
    public static void main(String[] args) {
        String host = "localhost";
        int port = 5432;
        String username = "root";
        String password = "root";

        Database database = new Database(host, port, username, password);

        database.connect(); // This is what makes a connection with our Postgresql server
    }
}

As you can see, connection is really easy.

Disconnecting from a database

If you want to flush out the connection you have, you can call Database#disconnect() and that should do the trick for you.

Troubleshooting

Here are some basic troubleshooting tips, if nothing seems to help you please make an Issue!

  • Make sure your credentials are correct!
  • Make sure your host string is either an ip or website that doesn't contain http or https. Example String host = "1.1.1.1"

Advanced

All the method information and parameters explanation can be found described in great detail on the Javadocs

Clone this wiki locally