PreparedStatment ps = null;
public void executeQueries(){
try{
ps = conn.prepareStatement(Query1);
// Execute Query1 here and do the processing.
ps = conn.prepareStatement(Query2);
// Execute Query2 here and do the processing.
//... more queries
}catch(){}
finally{
ps.close(); // At this point would the caching of queries in DB be lost?
}
}
在我的应用程序中,我经常调用方法 executeQueries()
。
我的问题是,如果我在方法(我经常使用)中的 finally block 中关闭 PreparedStatement
,数据库系统会删除缓存吗?如果是,我可以为整个应用程序创建一个全局 PreparedStatement
吗,因为我的应用程序中有大量查询数据库的 JAVA CLASSES。
谢谢!
更新:问题已被标记为重复,但链接的线程根本没有回答我的问题。 AFAIK,数据库系统将执行的查询存储在缓存中。它还存储他们的执行计划。这是 PreparedStatement
比 Statement
表现更好的地方。但是,我不太确定在关闭 PreparedStatement
后是否删除了与查询相关的信息。
最佳答案
特别是关于 MySQL,根据
8.10.3 Caching of Prepared Statements and Stored Programs
The server maintains caches for prepared statements and stored programs on a per-session basis. Statements cached for one session are not accessible to other sessions. When a session ends, the server discards any statements cached for it.
因此关闭 PreparedStatement
不会从缓存中删除语句,但关闭 Connection
可能会。
...除非应用程序使用连接池,在这种情况下关闭Connection
不一定会结束数据库 session ;它可能会保持 session 打开,并将连接返回到池中。
还有一个问题是,这些语句是否真的在服务器上准备好了。这是由 useServerPrepStmts
连接字符串属性控制的。 IIRC,默认情况下,服务器端准备好的语句不启用。
关于java - 如果我关闭 PreparedStatement,数据库中的缓存会丢失吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54284506/