在 MySQL 中一起使用准备好的语句和连接池
目前,对于每个查询,都会创建并重用一个准备好的语句。 我没有使用任何连接池。 C3P0 是一个被广泛推荐的库。
但是,由于PreparedStatement 与连接相关联。 在池化环境中,连接将返回到池中,从而有效地使PreparedStatement 无法使用。 我的这个结论正确吗? 有没有办法将Prepared Statement和连接池一起使用?
更新:这是独立的应用程序。 因此,我不能仅仅为了正确使用连接池而使用框架。
Presently, for each query, a Prepared Statement is created and reused. I am not using any connection pool. C3P0 is a widely recommended library for the same.
But, as a PreparedStatement is tied to a connection. In the pooled environment, the connections are returned to the pool, effectively making PreparedStatement unusable. Am I correct about this conclusion? Is there any way to use Prepared Statement and connection pooling together?
Update: This is stand-alone application. So, I cannot use a framework just to get connection pooling right.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当我看到《高性能 MySQL》中的这份材料时,我觉得你必须对 MySQL 配置进行一些超出您在 Java 中设置的操作。 您编辑过 my.cnf 文件吗?
另外,您是否查看过有关该主题的其他问题?
编辑:Spring 是一种可以帮助进行池化的框架,非常适合独立应用程序。
When I saw this material from "High Performance MySQL", it made me think that you had to do something to your MySQL configuration above and beyond anything you'd set in Java. Have you edited your my.cnf file?
Also, did you look at other SO questions on the topic?
EDIT: Spring is one framework that can help with pooling that's perfectly well-suited to stand-alone applications.
这取决于您使用的池机制。 大多数 Java EE 应用服务器都有连接池实现,其中池中的每个连接都有一个准备好的语句缓存。 因此准备好的语句以及连接都被重用。 我不知道有任何独立的池机制具有此功能。
It depends on the pooling mechanism you use. Most Java EE appservers have connection pool implementations where there is a prepared statement cache alongwith each connection in the pool. So the prepared statements are reused as well as the connections. I am not aware of any standalone pooling mechanisms though which have this functionality.
我相信如果您关闭连接,PreparedStatement 将“丢失”,但只要同一连接保持打开状态,相同的PreparedStatement 就应该可用。 您应该查看 Spring 使用 JdbcTemplate 为您完成此操作。 它会抽象掉所有这些,所以你不必担心它。 只需传递一个数据源就可以了。
以下是如何使用 c3p0 作为 DataSource 对象: http://forum.springframework.org /showthread.php?t=13078
然后,您可以创建一个 JdbcTemplate bean 并将数据源作为构造函数参数传入,然后将 JdbcTemplate 注入到您正在使用的任何 DAO 对象中。
I believe if you close the connection the PreparedStatement will be "lost", but as long as the same connection remains open, the same PreparedStatement should be usable. You should look at Spring to do this for you using a JdbcTemplate. It will abstract away all of that so you don't have to worry about it. Just pass it a DataSource and you're good to go.
Here's how you can use c3p0 as a DataSource object: http://forum.springframework.org/showthread.php?t=13078
You can then make a JdbcTemplate bean and pass in the datasource as a constructor argument, and then inject the JdbcTemplate into whatever DAO objects you're using.