jdbc连接池连不上mysql80_JDBC MySql连接池实践可避免连接池耗尽-问答-阿里云开发者社区-阿里云...

异常表明应用程序代码的典型情况是数据库连接泄漏。你需要确保你获得和关闭所有的人(Connection,Statement 和 ResultSet)在try-with-resources按照正常的JDBC成语在非常相同的方法块的块。

public void create(Entity entity) throws SQLException { try ( Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(SQL_CREATE); ) { statement.setSomeObject(1, entity.getSomeProperty()); // ... statement.executeUpdate(); } } 或者,当您不使用Java 7时,请执行以下try-finally步骤。关闭它们finally将保证在有例外情况下也将它们关闭。

public void create(Entity entity) throws SQLException { Connection connection = null; PreparedStatement statement = null;

try {

connection = dataSource.getConnection();

statement = connection.prepareStatement(SQL_CREATE);

statement.setSomeObject(1, entity.getSomeProperty());

// ...

statement.executeUpdate();

} finally {

if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}

if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}

}

} 是的,即使使用连接池,您仍然需要自己关闭连接。初学者常见的错误是,他们认为它将自动处理结局。这是不正确的。连接池即返回包装的连接,该连接在close()中执行以下操作:

public void close() throws SQLException { if (this.connection is still eligible for reuse) { do not close this.connection, but just return it to pool for reuse; } else { actually invoke this.connection.close(); } } 不关闭它们将导致连接不会释放回池以供重用,因此它将一次又一次获取新的连接,直到数据库用尽连接,这将导致应用程序崩溃。来源:stack overflow

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值