postgresql - Apache Tomcat 连接到 PostgreSQL 数据库(通过 JDBC 驱动程序)

标签 postgresql tomcat tomcat7 postgresql-9.3

我已经安装了 PostgreSQL 9.5.2 (rhel 6.7 x64) 和 Apache Tomcat 7.0.73(x64 rhel 6.7) 之后我下载了 postgresql-9.4.1212.jar jar 文件并粘贴到 Catalina_home/Lib 路径并添加这个跟随content.xml文件

<Resource auth="Container" name="jdbc/postgres" type="javax.sql.DataSource" user="sarkhan" password="1"
            driverClassName="org.postgresql.Driver" url="jdbc:postgresql://172.29.92.162:5432" maxActive="150"
            schema="test" maxIdle="4"/>

将以下内容添加到 web.xml 文件

<resource-ref>
    <description>postgreSQL Datasource</description>
    <res-ref-name>jdbc/postgres</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

那么我如何测试 Apache Tomcat 服务器是否已连接到 PostgreSQL 数据库服务器?

最佳答案

Tomcat 给出了JNDI Datasource HOW-TO 的引导,具体来说:

  1. Accessing the datasource

    When accessing the datasource programmatically, remember to prepend java:/comp/env to your JNDI lookup, as in the following snippet of code. Note also that "jdbc/postgres" can be replaced with any value you prefer, provided you change it in the above resource definition file as well.

InitialContext cxt = new InitialContext();
if ( cxt == null ) {
   throw new Exception("Uh oh -- no context!");
}

DataSource ds = (DataSource) cxt.lookup( "java:/comp/env/jdbc/postgres" );

if ( ds == null ) {
   throw new Exception("Data source not found!");
}

关于postgresql - Apache Tomcat 连接到 PostgreSQL 数据库(通过 JDBC 驱动程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40997191/

相关文章:

Tomcat、Intellij 和 DCEVM 配置

java - jasper 上的远程 MYSQL 报告错误 : com. 找不到 mysql.jdbc.Driver

tomcat7 - 无法远程连接到服务器(端口 8080 : Connection refused)

log4j:无法识别的元素滚动策略

database - 根据特定字段删除重复行

postgresql - 优化也适用于 "no rows"的 max() 聚合

java - 在外部 Tomcat 中部署 war 时,Springboot 端点失败

java - Spring Boot 忽略来自外部 application.properties 的日志记录级别

postgresql - 如何在复合类型的 Postgres 数组中存储双引号?

php - 如果已升级,请注意 : Need to manually update the pg_stats_reporter. ini