3

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.

4

2 回答 2

4

我建议让你的类成为java.io.Closeable的实现者。根据这个接口,你必须实现void close() throws IOException类的所有客户端都会调用它,因为Closeable在使用后关闭类是一个好习惯。

于 2012-05-29T11:35:09.083 回答
4

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

这将使您能够更快地获得连接,并且您不必过多地修改您的类。如果您需要扩展应用程序,数据库连接池是一项很棒的技术。

另一个好处是您的数据库连接池将由某种驱动程序管理,该驱动程序将负责打开连接、保持连接、在需要时增加连接池,并在未使用一定数量的额外连接时缩小连接池。时间。这将类似于您尝试在构造函数和终结方法中实现的代码。

一般而言,您仅在需要时才获取数据库连接并尽快释放它。

于 2012-05-29T11:40:22.050 回答