简体   繁体   English

将java.sql.Connection转换为PGConnection

[英]Cast java.sql.Connection to PGConnection

I want to upload a file in PostgreSQL using Tomcat: 我想使用Tomcat在PostgreSQL中上传文件:

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

I tried to cast the conn object this way: 我试图通过这种方式转换conn对象:

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

I get 我懂了

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

I also tried: 我也尝试过:

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

I get 我懂了

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

LargeObjectManager pgCon = pgCon.getLargeObjectAPI();

What is the proper way to implement the code? 实施代码的正确方法是什么?

PS 聚苯乙烯

I tried this: 我尝试了这个:

PGConnection pgConnection = null;

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

LargeObjectManager lobj = pgConnection.getLargeObjectAPI();

But I get NPE at this line LargeObjectManager lobj = pgConnection.getLargeObjectAPI(); 但是我在这一行得到了NPE LargeObjectManager lobj = pgConnection.getLargeObjectAPI();

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

For me this worked: 对我来说,这工作:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM