PostgreSQL数据库无法连接Tomcat 10.0.27服务器,遇500错误求助
解决PostgreSQL连接Tomcat 10.0.27时Connection为null的问题
根据你提供的代码和报错信息,connection为null的核心原因是DBConnection.getConnectionToDatabase()方法未能成功建立数据库连接,以下是具体排查和修复步骤:
1. 确认PostgreSQL JDBC驱动适配Tomcat 10
Tomcat 10基于Jakarta EE规范,必须使用Jakarta版本的PostgreSQL驱动(不能用传统Java EE版本):
- 下载对应版本的驱动(如
postgresql-42.6.0.jar或更高版本,需支持Jakarta) - 将驱动文件放到项目的
WEB-INF/lib目录,或Tomcat安装目录的lib文件夹下,确保部署时能被类加载器识别
2. 验证数据库连接参数正确性
检查getConnection方法中的参数:
- 端口:确认本地PostgreSQL服务监听的是5432端口(默认端口),可通过pgAdmin或
psql -p 5432 -U postgres命令测试连通性 - 数据库名:登录PostgreSQL控制台,执行
\l命令查看是否存在hplus数据库 - 用户名密码:确认
postgres用户的密码是否为空,若PostgreSQL设置了密码,需填写正确密码,不能留空字符串
3. 确保PostgreSQL服务处于运行状态
- Windows:打开系统服务列表,找到
postgresql-x64-xx服务,确认状态为“正在运行” - Linux:执行
systemctl status postgresql命令,查看服务是否启动
4. 修复DBConnection类的潜在问题
- 修正混淆的日志信息:将
System.out.println("MySQL JDBC Driver Registered!");改为System.out.println("PostgreSQL JDBC Driver Registered!"); - 手动注册驱动(适配部分旧环境):在try块中添加
Class.forName("org.postgresql.Driver");,确保驱动被加载,修改后的代码:
public static Connection getConnectionToDatabase() { Connection connection = null; try { Class.forName("org.postgresql.Driver"); System.out.println("PostgreSQL JDBC Driver Registered!"); connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/hplus", "postgres", "你的密码"); } catch (ClassNotFoundException | SQLException e) { System.out.println("Connection Failed! Check output console"); e.printStackTrace(); } if (connection != null) { System.out.println("Connection made to DB!"); } return connection; }
5. 查看详细错误日志
当前代码中e.printStackTrace()的输出会打印到Tomcat的日志文件中(通常在Tomcat安装目录/logs/catalina.out),查看具体的SQLException信息可快速定位问题:
No suitable driver found:驱动未正确加载FATAL: password authentication failed for user "postgres":用户名或密码错误FATAL: database "hplus" does not exist:目标数据库不存在
6. 修复SQL注入风险(额外优化)
你的searchProducts方法使用字符串拼接构造SQL语句,存在严重的SQL注入风险,建议改用PreparedStatement,同时使用try-with-resources语法自动关闭资源:
public List<Product> searchProducts(String searchString) { Product product = null; List<Product> products = new ArrayList<>(); try(Connection connection = DBConnection.getConnectionToDatabase()){ String sql = "select * from products where product_name like ?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, "%" + searchString + "%"); ResultSet set = statement.executeQuery(); while(set.next()){ product= new Product(); product.setProductId(set.getInt("product_id")); product.setProductImgPath(set.getString("image_path")); product.setProductName(set.getString("product_name")); products.add(product); } } catch(SQLException exception){ exception.printStackTrace(); } return products; }
内容的提问来源于stack exchange,提问作者wxist
相关产品推荐
相关产品推荐

