使用 Java servlet 时何时打开以及何时关闭 mysql 连接?
是否可以在 init
方法中打开连接并在 destroy
方法中关闭它?另外,打开 mysql 数据库连接的最佳方法是什么。目前我正在使用这个:
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://" + ipaddress + "?user=" + user + "&password=" + pass);
但我在某处读到这效率低下,我应该使用连接池。怎么做呢?
Is it ok to open a connection in the init
method and close it in the destroy
method? Also what's the best way to open a connection to a mysql database. Currently I'm using this:
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://" + ipaddress + "?user=" + user + "&password=" + pass);
But I read somewhere that this is inefficient and I should use connection pool. How to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我强烈建议使用连接池,无论是明确的(例如 c3p0)还是由 servlet 提供的连接池容器。
在需要时打开数据库连接,然后尽快关闭它 - 连接池将处理真正的网络连接。
除非您这样做,否则您的整个应用程序最终将只有一个连接 - 这意味着您一次只能处理一个查询,并且所有代码都需要围绕数据库查询进行同步。您肯定希望多个完全独立的查询能够同时执行吗?您无法通过单个连接来完成此操作。
至于在配置了适当的连接池后打开连接的最佳方法 - 您很可能最终仍然使用DriverManager.getConnection(),但指定连接池而不是直接指定mysql。
I would strongly suggest using a connection pool, either explicitly (such as c3p0) or one provided by your servlet container.
Open your database connection when you need it, then close it as soon as you can - the connection pool will take care of the real network connection.
Unless you do this, you'll end up with one connection for your whole application - which means you can only process one query at a time, and all your code needs to synchronize around database queries. Surely you want multiple entirely-independent queries to be able to execute simultaneously? You can't do this with a single connection.
As for the best way of opening a connection having configured an appropriate connection pool - you may well still end up using
DriverManager.getConnection()
, but specifying the connection pool instead of mysql directly.