App overview screenshotSQL and Database Guides
PostgresMySQL
Try our free SQL Client
Tools
Connecting to Postgres
Connecting to drivers
Installing Postgres
Setting up Postgres
Postgres   >   
Connecting to drivers   >   
Postgres with Java

Learn How to Connect PostgreSQL with Java

If you’re working on a Java app, you often need a database to store information. PostgreSQL is one of the most popular database systems available today. In this guide, we’ll walk you through how to connect your Postgres with Java.

What You’ll Need

Installing JDBC

In order to create Java programs that can interact with a PostgreSQL database, you’ll need to install the JDBC driver. You can get the latest version of JDBC4 here. Add the JDBC .jar file to your classpath.

Note: JDBC4 is for JDK 1.6+. If you are still running JDK 1.4 or 1.5, you can download JDBC3 here. You will also need to register the driver using: Class.forName("org.postgresql.Driver"); or DriverManager.registerDriver(new org.postgresql.Driver());.

Connecting to your PostgreSQL Database Using JDBC

You’ll need to have your Postgres credentials. You can use this guide to find them.

Once you have your credentials, import the JDBC package (java.sql.*) and get a new connection instance using DriverManager.getConnection()

String url = “jdbc:postgresql://localhost:5432/myDB”;
String user = “myUser”;
String password = “myPassword”;
Connection myConn = DriverManager.getConnection(url, user, password);

Connection urls follow the structure jdbc:postgresql://host:port/database.

Querying Your Database

Once you have established your connection, you can query your Postgres database using Java. To create and execute a query, use JDBC’s createStatement() and executeQuery() methods:

Statement myStmt = myConn.createStatement(); 
ResultSet results = myStmt.executeQuery(“SELECT ‘Arctype Archive: Your #1 Database Resource’ as message”);

You can also pass variables to a statement using JDBC’s PreparedStatement object and prepareStatement() method:

String sql = “INSERT INTO Users(username, email) VALUES(?,?) RETURNING *”;
String username = “Arctype”;
String email = “test@arctype.com”;
PreparedStatement myStmt = myConn.prepareStatement(sql);
myStmt.setString(1, username);
myStmt.setString(2, email);
ResultSet results = myStmt.executeQuery();

Using an SQL Client with Postgres and Java

Now that you’ve connected Postgres to your Java project, you often need to add or edit data. We recommend using an SQL client to do so. Check out our guide for setting up Postgres with Arctype in this tutorial.

Want to ask for help on databases or SQL? Join our Discord community.