为什么我们应该关闭 JDBC 中的连接?如果我们不这样做,会发生什么 [英] Why we should close the connection in JDBC? If we don't do it, what will happen

查看:50
本文介绍了为什么我们应该关闭 JDBC 中的连接?如果我们不这样做,会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中与数据库通信,我们经常按照以下步骤进行:

Communicate with the database in java, we often follow these steps:

  1. 加载驱动程序
  2. 建立连接
  3. 创建一个语句或PreparedStatement
  4. 获取 ResultSet
  5. 关闭连接

我很困惑我们应该关闭连接,都说创建连接很昂贵,所以我们为什么不能这样做:

I am confused that we should close connection, all say that create a connection is expensive, so why we can't do like this:

static
    {
        try
        {
            connection = DriverManager.getConnection(connectorURL,
                    user, password);
        } catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

我们只是将连接创建为单例,并在任何地方使用它.不能吗?如果我这样使用,会发生什么?

We just create a connection as a singleton, and use it everywhere. Couldn't it? If I use it like this, what will happen?

如果我不关闭连接,会发生什么?

And if I don't close the connection, what will happen?

另外,我们将使用一个连接池,它会在池中创建一些连接,我们从池中获取连接,池中的连接也不会关闭,为什么如果我们不使用池,如果我们不使用,我们需要按照步骤关闭连接吗?

Also, we will use a connection pool, it will create some connections in the pool, and we get the connection from the pool, the connection in the pool also don't close, why if we don't use pool, we need follow the steps and close the connection if we don't use?

很迷茫,不知道原理是什么.请帮我.谢谢.

It's so confused and I don't know the what's the principle. Please help me. Thanks.

推荐答案

如果不关闭连接,会导致连接内存泄漏.在应用程序服务器/Web 服务器关闭之前,即使用户注销,连接仍将保持活动状态.

If we don't close the connection, it will lead to connection memory leakage. Until application server/web server is shut down, connection will remain active, even if the user logs out.

还有其他原因.假设数据库服务器有 10 个可用连接,并且有 10 个客户端请求连接.如果数据库服务器授予所有这些请求,并且在使用后它们没有关闭,则数据库服务器将无法为另一个请求提供任何其他连接.出于这个原因,我们需要关闭它们 - 这是强制性的.

There are additional reasons. Suppose database server has 10 connections available and 10 clients request for the connection. If the database sever grants all of them, and after their usage they are not closed, the database server would not be able to provide any other connection for another request. For that reason we need to close them - it is mandatory.

此外,它可能会导致一些关于数据库完整性的恶作剧.

Furthermore, it might lead to some mischievous activities regarding the integrity of the database.

这篇关于为什么我们应该关闭 JDBC 中的连接?如果我们不这样做,会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆