在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
本文为大家分享了MySQL预编译功能,供大家参考,具体内容如下 1、预编译的好处 大家平时都使用过JDBC中的PreparedStatement接口,它有预编译功能。什么是预编译功能呢?它有什么好处呢? 2、MySQL执行预编译 MySQL执行预编译分为如三步: 3、使用Statement执行预编译 使用Statement执行预编译就是把上面的SQL语句执行一次。 Connection con = JdbcUtils.getConnection(); Statement stmt = con.createStatement(); stmt.executeUpdate("prepare myfun from 'select * from t_book where bid=?'"); stmt.executeUpdate("set @str='b1'"); ResultSet rs = stmt.executeQuery("execute myfun using @str"); while(rs.next()) { System.out.print(rs.getString(1) + ", "); System.out.print(rs.getString(2) + ", "); System.out.print(rs.getString(3) + ", "); System.out.println(rs.getString(4)); } stmt.executeUpdate("set @str='b2'"); rs = stmt.executeQuery("execute myfun using @str"); while(rs.next()) { System.out.print(rs.getString(1) + ", "); System.out.print(rs.getString(2) + ", "); System.out.print(rs.getString(3) + ", "); System.out.println(rs.getString(4)); } rs.close(); stmt.close(); con.close(); 4、useServerPrepStmts参数 默认使用PreparedStatement是不能执行预编译的,这需要在url中给出useServerPrepStmts=true参数(MySQL Server 4.1之前的版本是不支持预编译的,而Connector/J在5.0.5以后的版本,默认是没有开启预编译功能的)。 例如:jdbc:mysql://localhost:3306/test?useServerPrepStmts=true Connection con = JdbcUtils.getConnection(); String sql = "select * from t_book where bid=?"; PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setString(1, "b1"); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { System.out.print(rs.getString(1) + ", "); System.out.print(rs.getString(2) + ", "); System.out.print(rs.getString(3) + ", "); System.out.println(rs.getString(4)); } pstmt.setString(1, "b2"); rs = pstmt.executeQuery(); while(rs.next()) { System.out.print(rs.getString(1) + ", "); System.out.print(rs.getString(2) + ", "); System.out.print(rs.getString(3) + ", "); System.out.println(rs.getString(4)); } rs.close(); pstmt.close(); con.close(); 5、cachePrepStmts参数 当使用不同的PreparedStatement对象来执行相同的SQL语句时,还是会出现编译两次的现象,这是因为驱动没有缓存编译后的函数key,导致二次编译。如果希望缓存编译后函数的key,那么就要设置cachePrepStmts参数为true。例如: Connection con = JdbcUtils.getConnection(); String sql = "select * from t_book where bid=?"; PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setString(1, "b1"); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { System.out.print(rs.getString(1) + ", "); System.out.print(rs.getString(2) + ", "); System.out.print(rs.getString(3) + ", "); System.out.println(rs.getString(4)); } pstmt = con.prepareStatement(sql); pstmt.setString(1, "b2"); rs = pstmt.executeQuery(); while(rs.next()) { System.out.print(rs.getString(1) + ", "); System.out.print(rs.getString(2) + ", "); System.out.print(rs.getString(3) + ", "); System.out.println(rs.getString(4)); } rs.close(); pstmt.close(); con.close(); 6、打开批处理 MySQL的批处理也需要通过参数来打开:rewriteBatchedStatements=true 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持极客世界。 |
请发表评论