我想使用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();
实现代码的正确方法是什么?
P.S
我试过了:
PGConnection pgConnection = null;
if (conn.isWrapperFor(PGConnection.class))
{
pgConnection = conn.unwrap(PGConnection.class);
}
LargeObjectManager lobj = pgConnection.getLargeObjectAPI();
但我在这一行LargeObjectManager lobj = pgConnection.getLargeObjectAPI();
答案 0 :(得分:4)
if (dataSource.getConnection().isWrapperFor(PGConnection.class)) {
PGConnection pgConnection = dataSource.getConnection().unwrap(PGConnection.class);
}
答案 1 :(得分:0)
这对我来说很有效:
if (conn.isWrapperFor(org.apache.tomcat.dbcp.dbcp2.DelegatingConnection.class))
org.postgresql.jdbc.PgConnection pgConnection=(org.postgresql.jdbc.PgConnection)((org.apache.tomcat.dbcp.dbcp2.DelegatingConnection)conn).getInnermostDelegateInternal();