ORMLite --- 在 .commit 之后,.setAutoCommit --- 连接未关闭

ORMLite --- After .commit , .setAutoCommit --- Connection NOT closed

我在服务器和客户端制作的解决方案上使用 ORMLite。

在服务器端我使用 PostgreSQL,在客户端我使用 SQLite。在代码中,我使用相同的 ORMLite 方法,而不考虑管理的数据库(Postgres 或 SQLite)。我还使用了池连接。

我没有打开连接,当我需要 Sql 查询时,ORMLite 负责打开和关闭连接。

有时我使用以下代码在服务器端后台执行长时间操作,所以在 DB PostgreSql.

final ConnectionSource OGGETTO_ConnectionSource = ...... ;
final DatabaseConnection OGGETTO_DatabaseConnection =
     OGGETTO_ConnectionSource.getReadOnlyConnection( "tablename" ) ;
OGGETTO_DAO.setAutoCommit(OGGETTO_DatabaseConnection, false); 
// do long operation with Sql Queries ;
OGGETTO_DAO.commit(OGGETTO_DatabaseConnection);
OGGETTO_DAO.setAutoCommit(OGGETTO_DatabaseConnection, true);

我注意到打开的连接数增加了,因此过了一段时间,连接数大到停止服务器(Sql异常“连接到数据库的客户端太多”)。 我发现这是由于上面的代码片段,似乎在此片段之后连接未关闭 e 保持打开状态。 当然,我不能在末尾添加“OGGETTO_ConnectionSource.close()”,因为它会关闭池连接源。 如果我在末尾添加“OGGETTO_DatabaseConnection.close();”,它不起作用,打开的连接继续增加。

如何解决?

I discovered that it's due to the code snippet above, it seems that after this snippet the connection is not closed e remain open.

让我们来 RTFM。这是 ConnectionSource.getReadOnlyConnection(...) method 的 javadoc。我会引用:

Return a database connection suitable for read-only operations. After you are done,
you should call releaseConnection(DatabaseConnection).

您需要执行类似以下代码的操作:

DatabaseConnection connection = connectionSource.getReadOnlyConnection("tablename");
try {
   dao.setAutoCommit(connection false);
   try {
      // do long operation with Sql Queries
      ...
      dao.commit(connection);
   } finally {
      dao.setAutoCommit(connection, true);
   }
} finally {
   connectionSource.releaseConnection(connection);
}

顺便说一句,这大概就是TransactionManager.callInTransaction(...) method is doing although it has even more try/finally blocks to ensure that the connection's state is reset. You should probably switch to it. Here are the docs for ORMLite database transactions.