Introduction to Working with Databases in Java
Java is one of the most popular languages for creating enterprise applications, and working with databases is an integral part of such projects. In the modern world, developers often face a choice between relational and non-relational databases. In this article, we will thoroughly examine how to connect and work with two popular systems: PostgreSQL (relational database) and MongoDB (document-oriented NoSQL database) from Java. You will learn about driver configuration, performing CRUD operations, and best practices.
1. Working with PostgreSQL in Java
PostgreSQL is a powerful open-source object-relational database. To interact with it from Java, the JDBC (Java Database Connectivity) driver is used.
1.1 Connecting the PostgreSQL Driver
First, add the dependency to your project (Maven):
<dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.7.1</version></dependency>1.2 Establishing a Connection and Executing Queries
Example of connecting to the mydb database on a local server:
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;
public class PostgresExample { public static void main(String[] args) { String url = "jdbc:postgresql://localhost:5432/mydb"; String user = "postgres"; String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password); Statement stmt = conn.createStatement()) {
// Creating a table stmt.executeUpdate("CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name VARCHAR(100), email VARCHAR(100))");
// Inserting data stmt.executeUpdate("INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')");
// Retrieving data ResultSet rs = stmt.executeQuery("SELECT * FROM users"); while (rs.next()) { System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name")); } } catch (Exception e) { e.printStackTrace(); } }}1.3 Using PreparedStatement
To protect against SQL injection, always use PreparedStatement:
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";try (PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, "Bob"); pstmt.setString(2, "bob@example.com"); pstmt.executeUpdate();}2. Working with MongoDB in Java
MongoDB is a NoSQL database that stores data in JSON-like documents. The official MongoDB Java Driver is used to work with it.
2.1 Connecting the MongoDB Driver
Add the dependency to Maven:
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.11.1</version></dependency>2.2 Connecting to the Database and CRUD Operations
Example of working with the users collection:
import com.mongodb.client.MongoClient;import com.mongodb.client.MongoClients;import com.mongodb.client.MongoCollection;import com.mongodb.client.MongoDatabase;import org.bson.Document;
public class MongoDBExample { public static void main(String[] args) { // Connection try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) { MongoDatabase database = mongoClient.getDatabase("mydb"); MongoCollection<Document> collect