2014-03-05 44 views
4

我与使用JDBC(DB2)的数据库连接有问题。我最近在代码块上实现了事务管理(提交/回滚),并且对数据库上的所有查询/操作使用相同的连接。我们从来没有显式关闭每个查询/操作之间的连接。但是,在运行时,我们会得到一个异常,提示我们的连接无效(关闭/空)。当我逐步调试时,似乎连接字段意外变为空。它看起来是随机的,它不会发生在同一条线上。我相信我们不会自己关闭连接!我们在Tomcat中使用连接池。JDBC连接意外变为空

下面是一个代码示例:

try { 
connection = DB.getConnection(); 
connection.setAutoCommit(false); 
savepoint = connection.setSavepoint("avantModif"); 

    /* * Here are some queries and operations that runs without error 
when the connection is not null */  
connection.commit(); 

} 

catch(Exception e) { 

    if (connection != null && !connection.isClosed() && savepoint != null) 
     {   
      connection.rollback(savepoint); 
     } 

    throw e; 
} 

finally 
{ 
if(connection != null){  
    connection.close(); 

} 

这里是一个调试器屏幕截图示出连接对象内容:

enter image description here

这里是在Tomcat中的server.xml连接池定义:

<Resource 
    name="jdbc/dbcpGlobal" 
    auth="Container" 
    type="javax.sql.DataSource" 
    driverClassName="com.ibm.as400.access.AS400JDBCDriver" 
    url="jdbc:as400://lvq400/apilib;naming=system;errors=full;date format=iso;prompt=false;trace=false;reconnect=true" 
    username="[here_is_our_username]" password="[here_is_our_password]" 
    maxIdle="7" maxActive="15" maxWait="5" 
    removeAbandoned="true" removeAbandonedTimeout="120" logAbandoned="true" 
    testOnBorrow="true" testOnReturn="true" validationQuery="select 1 from sysibm/sysdummy1" /> 

对象不是真的null,其内容变为空!

是否有任何JDBC连接内容会变为空的原因?

+4

什么*究竟*你的意思是“连接对象内容”?如果您提供堆栈跟踪和一些示例代码,帮助您会容易得多... –

+0

您现在有更多的细节! – Marc

+0

好的,谢谢。现在,'DB.getConnection()'做了什么?您是否在多个线程中使用相同的连接? –

回答

0

我敢肯定,你实际上应该关闭连接。由于你得到的是一个代理对象,“关闭”它只会将它返回给池。我猜测Tomcat在某些时候开始扼杀你的连接,因为它们似乎被抛弃了。发生这种情况时日志中是否有任何内容,因为您有logAbandoned =“true”?

+0

感谢您的回复。我们确保我们记录了Tomcat日志中的所有异常,并且当我们尝试执行sql查询时,我们可以看到的唯一异常就像“错误:连接已关闭”。当我们停止使用Connection对象上的事务(提交,回滚)时,问题就消失了。如果发生任何异常,我们设法手动回滚。问题解决了,但我仍然不知道是什么原因造成的! – Marc