Java 中连接 PostgreSQL数据库

2024-12-18 0 213

在 Java 中连接 PostgreSQL(PG)数据库,可以使用 JDBC(Java Database Connectivity)。以下是详细的步骤和示例代码,帮助您在 Java 项目中连接和操作 PostgreSQL 数据库。

1. 添加 PostgreSQL JDBC 驱动依赖

首先,您需要在项目中添加 PostgreSQL 的 JDBC 驱动依赖。如果您使用的是 Maven 或 Gradle 构建工具,可以通过以下方式添加依赖。
使用 Maven
在 pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.20</version> <!-- 请使用最新版本 -->
</dependency>

使用 Gradle
在 build.gradle 文件中添加以下依赖:

dependencies {
    implementation 'org.postgresql:postgresql:42.2.20' // 请使用最新版本
}

2. 配置数据库连接

接下来,您需要配置数据库连接字符串。以下是一个基本的配置示例。

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

public class PostgreSQLJDBCExample {
    public static void main(String[] args) {
        // 数据库连接字符串
        String url = "jdbc:postgresql://localhost:5432/mydatabase";
        String user = "myuser";
        String password = "mypassword";

        // 加载 PostgreSQL JDBC 驱动
        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("PostgreSQL JDBC Driver not found.");
            e.printStackTrace();
            return;
        }

        // 建立连接
        try (Connection connection = DriverManager.getConnection(url, user, password)) {
            if (connection != null) {
                System.out.println("Connected to the PostgreSQL server successfully.");
            } else {
                System.out.println("Failed to make connection!");
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

3. 执行查询

一旦建立了连接,可以执行 SQL 查询。以下是一个简单的示例,展示如何执行查询并处理结果。

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

public class PostgreSQLJDBCExample {
    public static void main(String[] args) {
        String url = "jdbc:postgresql://localhost:5432/mydatabase";
        String user = "myuser";
        String password = "mypassword";

        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("PostgreSQL JDBC Driver not found.");
            e.printStackTrace();
            return;
        }

        try (Connection connection = DriverManager.getConnection(url, user, password);
             Statement statement = connection.createStatement()) {

            String sql = "SELECT * FROM my_table";
            ResultSet resultSet = statement.executeQuery(sql);

            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                System.out.println("ID: " + id + ", Name: " + name);
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

4. 插入数据

可以使用 PreparedStatement 来插入数据,以防止 SQL 注入攻击。

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

public class PostgreSQLJDBCExample {
    public static void main(String[] args) {
        String url = "jdbc:postgresql://localhost:5432/mydatabase";
        String user = "myuser";
        String password = "mypassword";

        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("PostgreSQL JDBC Driver not found.");
            e.printStackTrace();
            return;
        }

        String sql = "INSERT INTO my_table (id, name) VALUES (?, ?)";

        try (Connection connection = DriverManager.getConnection(url, user, password);
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {

            preparedStatement.setInt(1, 1);
            preparedStatement.setString(2, "Sample Document");
            preparedStatement.executeUpdate();

            System.out.println("Data inserted successfully.");
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

5. 更新数据

同样,使用 PreparedStatement 来更新数据。

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

public class PostgreSQLJDBCExample {
    public static void main(String[] args) {
        String url = "jdbc:postgresql://localhost:5432/mydatabase";
        String user = "myuser";
        String password = "mypassword";

        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("PostgreSQL JDBC Driver not found.");
            e.printStackTrace();
            return;
        }

        String sql = "UPDATE my_table SET name = ? WHERE id = ?";

        try (Connection connection = DriverManager.getConnection(url, user, password);
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {

            preparedStatement.setString(1, "Updated Document");
            preparedStatement.setInt(2, 1);
            preparedStatement.executeUpdate();

            System.out.println("Data updated successfully.");
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

6. 删除数据

使用 PreparedStatement 来删除数据。

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

public class PostgreSQLJDBCExample {
    public static void main(String[] args) {
        String url = "jdbc:postgresql://localhost:5432/mydatabase";
        String user = "myuser";
        String password = "mypassword";

        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("PostgreSQL JDBC Driver not found.");
            e.printStackTrace();
            return;
        }

        String sql = "DELETE FROM my_table WHERE id = ?";

        try (Connection connection = DriverManager.getConnection(url, user, password);
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {

            preparedStatement.setInt(1, 1);
            preparedStatement.executeUpdate();

            System.out.println("Data deleted successfully.");
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

7. 处理事务

在某些情况下,可能需要处理事务以确保数据的一致性。

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

public class PostgreSQLJDBCExample {
    public static void main(String[] args) {
        String url = "jdbc:postgresql://localhost:5432/mydatabase";
        String user = "myuser";
        String password = "mypassword";

        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("PostgreSQL JDBC Driver not found.");
            e.printStackTrace();
            return;
        }

        try (Connection connection = DriverManager.getConnection(url, user, password)) {
            connection.setAutoCommit(false); // 关闭自动提交

            String insertSql = "INSERT INTO my_table (id, name) VALUES (?, ?)";
            String updateSql = "UPDATE my_table SET name = ? WHERE id = ?";

            try (PreparedStatement insertStatement = connection.prepareStatement(insertSql);
                 PreparedStatement updateStatement = connection.prepareStatement(updateSql)) {

                insertStatement.setInt(1, 1);
                insertStatement.setString(2, "Sample Document");
                insertStatement.executeUpdate();

                updateStatement.setString(1, "Updated Document");
                updateStatement.setInt(2, 1);
                updateStatement.executeUpdate();

                connection.commit(); // 提交事务
                System.out.println("Transaction committed successfully.");
            } catch (SQLException e) {
                connection.rollback(); // 回滚事务
                System.out.println("Transaction rolled back.");
                e.printStackTrace();
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

总结

通过以上步骤,可以在 Java 项目中成功连接和操作 PostgreSQL 数据库。JDBC 提供了丰富的 API 来执行各种数据库操作,包括查询、插入、更新和删除数据。确保您的 PostgreSQL 实例正在运行,并且客户端配置正确,以便顺利进行这些操作。如果遇到任何问题,可以参考 PostgreSQL 和 JDBC 的官方文档或社区资源以获取更多帮助。

平台声明:以上文章转载于《CSDN》,文章全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,仅作参考。

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

原文链接:https://blog.csdn.net/shenjqiang/article/details/144560524

遇见资源网 JAVA Java 中连接 PostgreSQL数据库 http://www.ox520.com/157457.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务