简体   繁体   English

坚持PreparedStatements是否昂贵? (Java和JDBC)

[英]Is it expensive to hold on to PreparedStatements? (Java & JDBC)

I'm trying to figure out if it's efficient for me to cache all of my statements when I create my database connection or if I should only create those that are most used and create the others if/when they're needed.. 我正在试图弄清楚在创建数据库连接时是否有效缓存我的所有语句,或者我是否应该创建最常用的语句,并在需要时创建其他语句。

It seems foolish to create all of the statements in all of the client threads. 所有客户端线程中创建所有语句似乎很愚蠢。 Any feedback would be greatly appreciated. 任何反馈将不胜感激。

A bit decent database will already cache them. 一个像样的数据库将已经缓存它们。 Just fire Connection#prepareStatement() at the moment you actually need to execute the query. 在您实际需要执行查询时,只需触发Connection#prepareStatement() You actually also have no other choice since connection, statement and resultset ought to be acquired and closed in the shortest possible scope, ie in a try-finally block in the very same method as you execute the query. 您实际上也没有其他选择,因为应该在尽可能短的范围内获取和关闭连接,语句和结果集,即在与执行查询相同的方法中的try-finally块中。

Opening and closing the connection on every query in turn may indeed be expensive. 依次打开和关闭每个查询的连接可能确实很昂贵。 A common solution to that is using a connection pool , for example c3p0 . 一个常见的解决方案是使用连接池 ,例如c3p0

I think you're worrying too much, prepared statements already benefit from several level of caching: 我认为你太担心了,准备好的声明已经从几个级别的缓存中受益:

  • At the database level: a decent database will reuse the access plan for a given prepared statement. 在数据库级别:一个体面的数据库将重用给定预准备语句的访问计划。
  • At the connection pool level: a decent connection pool will cache PreparedStatement objects for each database connection in the pool (and return a cached PreparedStatement on subsequent calls to preparedStatement on a connection). 在连接池级别:一个合适的连接池将为池中的每个数据库连接缓存PreparedStatement对象(并在后续调用连接上的preparedStatement时返回缓存的PreparedStatement )。

So actually, I would even say that you might be looking in the wrong direction. 实际上,我甚至会说你可能会朝错误的方向看。 The best practice if you want to design a scalable solution is to use a connection pool and to not held a connection longer than needed and to release it (to release database resources) when you're done with it. 如果要设计可伸缩的解决方案,最佳做法是使用连接池,并且不需要比所需更长的连接,并在完成后释放它(释放数据库资源)。

This sounds to me like the kind of premature optimization that I wouldn't worry about until I have some information telling me that it mattered. 这听起来像是一种我不会担心的过早优化,直到我得到一些告诉我重要的信息。 If your database access is inefficient, I'd suspect your schema or access of values before I'd think of caching prepared statements. 如果您的数据库访问效率低下,我会在考虑缓存预准备语句之前怀疑您的模式或值的访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM