java如何连接pgsql
连接 PostgreSQL 数据库的 Java 实现
依赖准备
确保项目中包含 PostgreSQL JDBC 驱动依赖。Maven 项目可在 pom.xml 中添加:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.6.0</version>
</dependency>
基础连接代码
使用 java.sql.DriverManager 建立连接:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class PgSQLConnection {
private static final String URL = "jdbc:postgresql://localhost:5432/your_database";
private static final String USER = "your_username";
private static final String PASSWORD = "your_password";
public static Connection connect() throws SQLException {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
}
连接池配置(推荐) 使用 HikariCP 连接池示例:
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
public class PgSQLPool {
private static final HikariDataSource dataSource;
static {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:postgresql://localhost:5432/your_database");
config.setUsername("your_username");
config.setPassword("your_password");
config.setMaximumPoolSize(10);
dataSource = new HikariDataSource(config);
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}
SSL 连接配置 需在 URL 中添加参数:
String url = "jdbc:postgresql://host:port/database?ssl=true&sslmode=require";
异常处理建议 始终在 try-with-resources 中处理连接:
try (Connection conn = PgSQLConnection.connect();
Statement stmt = conn.createStatement()) {
// 执行查询或更新操作
} catch (SQLException e) {
e.printStackTrace();
}
注意事项

- 确保 PostgreSQL 服务已启动且防火墙允许访问
- 连接参数如
sslmode、connectTimeout可根据需求调整 - 生产环境建议使用连接池管理资源






