gpt4 book ai didi

postgresql - 使用 Postgres 配置 Tomcat 8

转载 作者:行者123 更新时间:2023-11-28 22:52:26 25 4
gpt4 key购买 nike

我想用 PostgreSQL 配置 Tomcat 8

我在 context.xml 中添加了这个

<Resource name="jdbc/DefaultDB" auth="Container" type="javax.sql.DataSource"
username="postgres" password="qwerty"
url="jdbc:postgresql://localhost:5432/crm"
driverClassName="org.postgresql.Driver"
initialSize="5" maxWait="5000"
maxActive="120" maxIdle="5"
validationQuery="select 1"
poolPreparedStatements="true"/>

然后我尝试运行这段 Java 代码:

public String init()
{
String user_name = null;
try
{
Context ctx = new InitialContext();
if (ctx == null)
throw new Exception("Boom - No Context");

DataSource ds = (DataSource) ctx.lookup("jdbc/DefaultDB");

if (ds != null)
{
Connection conn = ds.getConnection();

if (conn != null)
{
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("select id, user_name from user where username = " + user);
if (rst.next())
{
user_name = rst.getString("user_name");
}
conn.close();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}

return user_name;
}

但由于某种原因,在我添加此代码后,Tomcat 没有启动。你知道我哪里错了吗?

我在 Tomcat 日志文件中得到这个:

    28-Mar-2016 10:37:07.955 WARNING [localhost-startStop-1] org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory.getObjectInstance Name = DefaultDB Property maxActive is not used in DBCP2, use maxTotal instead. maxTotal default value is 8. You have set value of "120" for "maxActive" property, which is being ignored.
28-Mar-2016 10:37:07.956 WARNING [localhost-startStop-1] org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory.getObjectInstance Name = DefaultDB Property maxWait is not used in DBCP2 , use maxWaitMillis instead. maxWaitMillis default value is -1. You have set value of "5000" for "maxWait" property, which is being ignored.

javax.naming.NameNotFoundException: Name [jdbc/DefaultDB] is not bound in this Context. Unable to find [jdbc].

最佳答案

正如@a_horse_with_no_name 所说,您的查询是错误的。你的代码必须是这样的:

public String init()
{
String user_name = null;
try
{
Context ctx = new InitialContext();
if (ctx == null)
throw new Exception("Boom - No Context");
Context envCtx = (Context) ctx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/DefaultDB");

if (ds != null)
{
Connection conn = ds.getConnection();

if (conn != null)
{
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("select id, user_name from user where username = " + user);
if (rst.next())
{
user_name = rst.getString("user_name");
}
conn.close();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}

return user_name;
}

关于postgresql - 使用 Postgres 配置 Tomcat 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36253625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com