预编译参数:由驱动程序设定,而非数据库配置设定。
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/prepare_stmt_test?user=root&password=root&useServerPrepStmts=true&cachePrepStmts=true");
①开启预编译:useServerPstmts=true (Connector/J 5.0.5及之后默认false)
②开启预编译缓存:cachePrepStmts=true (一直默认false)
效率:
①开启预编译,不开启预编译缓存,效率低于非预编译执行;
②开启预编译同时开启预编译缓存,效率与非预编译执行几乎一样(同connect);
③预编译与预编译缓存只能在同connect中共享,当stms关闭后,每次调用都会重新预编译语句,效率反而低下。
建议:
因为预编译可以防止sql注入,所以建议预编译+缓存同时开启,且stms尽量使用同一个,不要每一个语句都去关闭。