Working with Databases in Java: PostgreSQL and MongoDB for Beginners
\n\nIn modern Java development, the ability to work with databases (DB) is one of the key skills. Whether you are creating a web application, a mobile service, or an enterprise system, you will need to store, retrieve, and process data. In this article, we will look at two popular database management systems (DBMS): the relational PostgreSQL and the document-oriented MongoDB. You will learn how to connect to them from a Java application, perform basic operations, and understand in which cases to choose one technology or the other. The material is aimed at beginner developers, so all code examples are as simple as possible and provided with comments.
\n\n1. Basics of Working with PostgreSQL in Java
\n\nPostgreSQL is a powerful open-source object-relational DBMS. To interact with it from Java, the JDBC (Java Database Connectivity) driver is used. Let's look at the step-by-step process of connecting and executing queries.
\n\n1.1. Driver Connection and Setup
\n\nFirst, you need to add a dependency to your project. If you are using Maven, add the following block to pom.xml:
<dependency>\n <groupId>org.postgresql</groupId>\n <artifactId>postgresql</artifactId>\n <version>42.7.1</version>\n</dependency>\n\nFor Gradle, add the line to build.gradle:
implementation 'org.postgresql:postgresql:42.7.1'\n\n1.2. Creating a Table and Inserting Data
\n\nSuppose we have a database testdb with a user user and password pass. Let's create a simple table users and add a few records.
import java.sql.*;\n\npublic class PostgresExample {\n public static void main(String[] args) {\n String url = "jdbc:postgresql://localhost:5432/testdb";\n String user = "user";\n String password = "pass";\n\n try (Connection conn = DriverManager.getConnection(url, user, password);\n Statement stmt = conn.createStatement()) {\n\n // Creating the table\n String createTableSQL = "CREATE TABLE IF NOT EXISTS users (" +\n "id SERIAL PRIMARY KEY, " +\n "name VARCHAR(100) NOT NULL, " +\n "email VARCHAR(100) UNIQUE)";\n stmt.executeUpdate(createTableSQL);\n System.out.println("Table created or already exists.");\n\n // Inserting data\n String insertSQL = "INSERT INTO users (name, email) VALUES " +\n "('Ivan Petrov', 'ivan@example.com'), " +\n "('Maria Smirnova', 'maria@example.com')";\n int rowsInserted = stmt.executeUpdate(insertSQL);\n System.out.println("Rows inserted: " + rowsInserted);\n\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }\n}\n\n1.3. Reading Data Using PreparedStatement
\n\nFor safe work with user input, use PreparedStatement. This prevents SQL injection.
String selectSQL = "SELECT * FROM users WHERE name LIKE ?";\ntry (PreparedStatement pstmt = conn.prepareStatement(selectSQL)) {\n pstmt.setString(1, "%Ivan%");\n ResultSet rs = pstmt.executeQuery();\n\n while (rs.next()) {\n int id = rs.getInt("id");\n String name = rs.getString("name");\n String email = rs.getString("email");\n System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);\n }\n} catch (SQLException e) {\n e.printStackTrace();\n}\n\nAs you can see, working with PostgreSQL in Java is standard and well-documented