code_junkie

How to use MySQL prepared statement caching?

Nov 11th, 2011
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.71 KB | None | 0 0
  1. Class.forName("com.mysql.jdbc.Driver");
  2. Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb" +
  3. "?cachePrepStmts=true", "user", "pass");
  4. for (int i = 0; i < 5; i++) {
  5. PreparedStatement ps = conn.prepareStatement("select * from MYTABLE where id=?");
  6. ps.setInt(1, 1);
  7. ps.execute();
  8. }
  9. conn.close()
  10.  
  11. Connection conn = DatabaseUtil.getConnection();
  12. PreparedStatement stmtUpdate = conn.prepareStatement("UPDATE foo SET bar=? WHERE id = ?);
  13. for(int id=0; id<10; id++){
  14. stmtUpdate.setString(1, "baz");
  15. stmtUpdate.setInt(2, id);
  16. int rows = stmtUpdate.executeUpdate();
  17. // Clear parameters for reusing the preparedStatement
  18. stmtUpdate.clearParameters();
  19. }
  20. conn.close();
Add Comment
Please, Sign In to add comment