【问题标题】:connection with db in try with resources not allows any operations在尝试使用资源时与 db 的连接不允许任何操作
【发布时间】:2022-07-20 00:37:34
【问题描述】:

我想对资源使用try,虽然我的程序在连接关闭后无法完成操作。

String conn = "jdbc:mysql://localhost:3306/test?&serverTimeZone=Europe/Moscow&useSSL=false&allowPublicKeyRetrieval=true";
try (Connection connection = DriverManager.getConnection( conn,"root","admin"))
   {
    return connection;
   } catch (SQLException e) {
  throw new RuntimeException(e);
}

我的项目是https://github.com/anatoliy19/1.1.3.git

【问题讨论】:

    标签: java mysql connection


    【解决方案1】:

    try-with-resources 块中分配的资源在您离开该块时关闭。因此,当您返回连接时,该连接将关闭。对连接的引用仍然有效,并且在不再引用之前不会被 GC。

    你可以这样想。如果这里返回的连接没有关闭,编译器什么时候知道应该关闭它?编译器无法知道这一点。

    您应该使用该块内的连接或自行管理关闭连接,而不是使用 try-with-resources。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-16
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多