在构造函数中打开数据库连接,我什么时候应该关闭它? [英] Opening a database connection in a constructor, when should I close it?

查看:375
本文介绍了在构造函数中打开数据库连接,我什么时候应该关闭它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我一直在想,只要使用对象,保持与数据库的连接打开,使数据库请求更快一点。所以我想在该类的构造函数中打开连接。
现在的问题是,我如何在我停止使用后关闭连接?我必须调用close()某处,不是吗?
我一直在阅读关于finalize()方法,但是人们似乎对这种方法在任何地方的使用持怀疑态度。我希望它有一个类似析构函数的东西,但Java没有这样,所以?

well, I've been thinking of making database requests a little faster by keeping the connection to the database open as long as the object is being used. So I was thinking of opening the connection in the constructor of that class. Now the question is, how can I close the connection after I stopped using? I have to call close() somewhere, don't I? I've been reading about the finalize() method, but people seemed to be skeptical about usage of this method anywhere at all. I'd expect it to have something like a destructor, but Java doesn't have that, so?

那么,任何人都可以给我一个解决方案?提前感谢。

So could anyone provide me with a solution? Thanks in advance.

推荐答案

我建议你宁愿实现数据库连接池,如果应用程序允许它。使用连接池将创建一个连接池并保持连接到数据库。然后,您的应用程序将从池中获取打开/未使用的连接,并使用它并将其返回到池中。

I would suggest that you rather implement database connection pooling if the application would allow it. With connection pooling a pool of connections would be created and stay connected to the database. Your application would then grab a open/unused connection from the pool use it and return it to the pool.

这将允许您更快地获取连接,您不必太多地修改类。如果你需要扩展你的应用程序,数据库连接池是一个伟大的技术。

This would allow you to acquire connections faster and you won't have to modify your classes too much. Database connection pooling is a great technique if you need to scale your application.

另一个好处是你的数据库连接池将由某种驱动程序保持打开连接,保持它们打开,如果需要则增大池,并且当在一定量的时间内不使用额外连接时缩小池。这将类似于您尝试在构造函数和finalization方法中实现的代码。

The other benefit is that your database connection pool will be managed by some sort of driver which will take care of opening connections, keeping them open, growing the pool if required and also shrinking the pool when extra connections are not used for a certain amount of time. This would be similar to the code you are trying to implement in the constructor and finalization methods.

一般来说,您只需在需要时才询问数据库连接,并尽快发布数据库连接。

Generally speaking you aqquire a database connection only when needed and release it as soon as possible.

这篇关于在构造函数中打开数据库连接,我什么时候应该关闭它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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