Working with Databases in Java: PostgreSQL and MongoDB for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Working with Databases in Java: PostgreSQL and MongoDB for Beginners



Modern Java development rarely goes without interacting with databases. Whether you are creating a web application, a mobile service, or an enterprise system, the ability to work with SQL and NoSQL databases is a mandatory skill. In this article, we will cover how to connect to PostgreSQL (relational DB) and MongoDB (document-oriented DB) from Java, perform basic operations, and avoid common mistakes.



The material is intended for beginner developers who are already familiar with the basics of Java (classes, methods, exceptions) and want to learn how to work with data. All code examples can be copied and run in your development environment.



1. Environment Setup and Dependencies



To work with databases in Java, you need to add the appropriate libraries. We will use Maven for dependency management. If you use Gradle or another build tool, the principle will be similar.



Dependencies for PostgreSQL (via JDBC)

<dependency>    <groupId>org.postgresql</groupId>    <artifactId>postgresql</artifactId>    <version>42.7.1</version></dependency>


Dependencies for MongoDB (official driver)

<dependency>    <groupId>org.mongodb</groupId>    <artifactId>mongodb-driver-sync</artifactId>    <version>4.11.1</version></dependency>


After adding the dependencies, update the project (Maven → Reload Project). Make sure the databases themselves are installed and running (locally or via Docker).



2. Working with PostgreSQL in Java



PostgreSQL is a classic relational database. JDBC (Java Database Connectivity) is used to interact with it from Java. Let's look at the full cycle: connection, table creation, data insertion and reading.



2.1. Connecting to the Database

Let's create a class PostgresConnector with a method to obtain a connection:

import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;

public class PostgresConnector { private static final String URL = "jdbc:postgresql://localhost:5432/testdb"; private static final String USER = "postgres"; private static final String PASSWORD = "your_password";

public static Connection getConnection() throws SQLException { return DriverManager.getConnection(URL, USER, PASSWORD); }}


2.2. Creating a Table and Inserting Data

We use Statement and PreparedStatement to execute SQL queries:

import java.sql.*;

public class PostgresExample { public static void main(String[] args) { String createTableSQL = "CREATE TABLE IF NOT EXISTS users (" + "id SERIAL PRIMARY KEY, " + "name VARCHAR(100) NOT NULL, " + "email VARCHAR(100) UNIQUE NOT NULL)";

String insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)";

try (Connection conn = PostgresConnector.getConnection(); Statement stmt = conn.createStatement()) {

// Create table stmt.execute(createTableSQL); System.out.println("Table users created (or already exists).");

// Insert data via PreparedStatement (safe from SQL injection) try (PreparedStatement pstmt = conn.prepareStatement(insertSQL)) { pstmt.setString(1, "Ivan Petrov"); pstmt.setString(2, "ivan@example.com"); pstmt.executeUpdate(); System.out.println("User added."); }

} catch (SQLException e) { e.printStackTrac

Blogs

Book Recommendations