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

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

问题描述

与Java中的数据库进行通信,我们通常遵循以下步骤:

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

  1. 加载驱动程序
  2. 获得连接
  3. 创建语句或PreparedStatement
  4. 获取ResultSet
  5. 关闭连接
  1. load a driver
  2. get a connection
  3. create a Statement or PreparedStatement
  4. get the ResultSet
  5. close the connection

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

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. Unless/until application server/web server is shut down, connection will remain activate even though 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 a connections 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天全站免登陆