gpt4 book ai didi

java - 将 java.sql.Connection 转换为 PGConnection

转载 作者:行者123 更新时间:2023-11-29 12:36:36 27 4
gpt4 key购买 nike

我想使用 Tomcat 在 PostgreSQL 中上传文件:

@Resource(name = "jdbc/DefaultDB")
private DataSource ds;
Connection conn = ds.getConnection();

我试图以这种方式转换 conn 对象:

PGConnection pgCon = ((org.apache.commons.dbcp.DelegatingConnection) conn).getInnermostDelegate();

我明白了

Caused by: java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp2.PoolingDataSource$PoolGuardConnectionWrapper cannot be cast to org.postgresql.PGConnection

我也试过:

Connection unwrap = conn.unwrap(Connection.class);
connSec = (org.postgresql.PGConnection) unwrap;

我明白了

java.sql.SQLException: Cannot unwrap to org.postgresql.PGConnection

LargeObjectManager pgCon = pgCon.getLargeObjectAPI();

实现代码的正确方法是什么?

附言

我试过这个:

PGConnection pgConnection = null;

if (conn.isWrapperFor(PGConnection.class))
{
pgConnection = conn.unwrap(PGConnection.class);
}

LargeObjectManager lobj = pgConnection.getLargeObjectAPI();

但是我在这一行得到了 NPE LargeObjectManager lobj = pgConnection.getLargeObjectAPI();

最佳答案

if (dataSource.getConnection().isWrapperFor(PGConnection.class)) {
PGConnection pgConnection = dataSource.getConnection().unwrap(PGConnection.class);
}

关于java - 将 java.sql.Connection 转换为 PGConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36986653/

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