How to use MySQL prepared statement caching?

情到浓时终转凉″ 提交于 2019-11-29 10:14:12

Is it possible to mimic this using pure JDBC?

Is this not in fact what you've done by moving your prepared statement call out of the loop?

I may be misunderstanding the way the MySQL cache works, but does the log file necessarily report the cache's work? It may be that Spring or Hibernate has its own intermediate cache that checks the prepared statements against those sent earlier. It might be that that you're seeing when you run the program with Spring. That would mean doing a bit of tracing with your system to see if the mysqld log is just reporting the statements it's been sent, regardless of how it deals with them.

You should prepare your statement only once, outside of the loop, and then bind the parameters in the loop. This is why prepared statements have bind parameters - so you can reuse the prepared statement.

Hibernate does exactly this, treating all SQL as a prepared statement behind the scenes, though you can obviously abuse this if you use literal rather than bind parameters.

You also need to set the statement cache size on the connection instance. I assume the default cache size is 0. Hence nothing would be cached.

First, your PreparedStatement is recreated in the loop, so the JDBC driver is allowed to discard the prepared data. So you asked for the ugly behaviour, and so you got it.

And then, PreparedStatement in MySQL are a chapter on its own. To have real caching, you have to request it explicitly via a connection property.

So you have to set the "cachePrepStmts" property to "true" to get caching on prepared statements. By default, that property is set to false.

@see the MySQL manual for your MySQL version for details

kosoant

You should prepare the statement outside the loop.

Connection conn = DatabaseUtil.getConnection();
PreparedStatement stmtUpdate = conn.prepareStatement("UPDATE foo SET bar=? WHERE id = ?");
for(int id=0; id<10; id++){
    stmtUpdate.setString(1, "baz");
    stmtUpdate.setInt(2, id);
    int rows = stmtUpdate.executeUpdate();
    // Clear parameters for reusing the preparedStatement
    stmtUpdate.clearParameters();
}
conn.close();

I don't know about mysql caching prepared statements, but this is the way JDBC prepared statements are supposed to be reused.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!