Mysql预编译

首先,我们要清楚一条sql的执行过程,明白什么是预编译

  1. 词法和语义解析
  2. 优化sql语句,制定执行计划
  3. 执行并返回结果

  但是很多情况,我们的一条sql语句可能会反复执行,或者每次执行的时候只有个别的值不同(比如query的where子句值不同,update的set子句值不同,insert的values值不同)。
  如果每次都需要经过上面的词法语义解析、语句优化、制定执行计划等,则效率就明显不行了。
  所谓预编译语句就是将这类语句中的值用占位符替代,可以视为将sql语句模板化或者说参数化,一般称这类语句叫Prepared Statements或者Parameterized Statements
  预编译语句的优势在于归纳为:一次编译、多次运行,省去了解析优化等过程;此外预编译语句能防止sql注入。
  当然就优化来说,很多时候最优的执行计划不是光靠知道sql语句的模板就能决定了,往往就是需要通过具体值来预估出成本代价。
摘自:https://www.cnblogs.com/micrari/p/7112781.html

其实在我看来预编译最大的作用是防止sql注入,just do it~~~

    @Before
    public void init() {
        //获取数据库连接
        final String DRIVER = "com.mysql.jdbc.Driver";
        final String URL = "jdbc:mysql://127.0.0.1:3306/employees?characterEncoding=utf-8&useSSL=true&verifyServerCertificate=false&useServerPrepStmts=true&cachePrepStmts=true";
        final String USER = "root";
        final String PWD = "";
        try {

            Class.forName(DRIVER);
            con = DriverManager.getConnection(URL, USER, PWD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    @After
    public void end() {
        try {
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

测试例子:

    @Test
    public void test1() throws SQLException {
        //非预编译
        String testSql = "select * from departments where dept_no = ";
        String args = "1 or 1=1";
        Statement statement=con.createStatement();
        statement.execute(testSql+args);
    }

    @Test
    public void test2() throws SQLException {
       //预编译
        String testSql = "select * from departments where dept_no = ?";
        String args = "1 or 1=1";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1,args);
        ps.execute();
    }

然后打开mysql的全日制,方法如下:

image.png

执行test,可以在log中看到


image.png

再来看下性能方面,主要体现在服务端的预编译

注意上面log截图部分

2018-05-15T08:27:04.468200Z  1912 Prepare   select * from employees where emp_no = ?
2018-05-15T08:27:04.470200Z  1912 Execute   select * from employees where emp_no = '1 or 1=1'

prepareexecute就是服务端预编译的体现,为什么说是服务端呢。按我的理解,其实所谓预编译应该是分本地jdbc和服务端两块的。本地你如果要用预编译,只要使用PreparedStatement就行了,这样就能达到防止sql注入的目的。换句话说,防止sql注入是jdbc实现的。
但是如果你要开启服务端的预编译,那就要在数据库连接带上useServerPrepStmts=true&cachePrepStmts=true这两个参数。
下面开始上测试数据:

static String sql = "select * from employees where emp_no = ?";
    @Test
    public void select() throws SQLException {
        long startTime = System.currentTimeMillis();
        for (int i = 10001; i < 30001; i++) {
            PreparedStatement ps = con.prepareStatement(sql);
            ResultSet rs = null;
            ps.setInt(1, i);
            try {
                rs = ps.executeQuery();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            rs.close();
            ps.close();
        }
        System.out.print(System.currentTimeMillis() - startTime + " ");
    }
    public static void main(String[] args) throws SQLException {
        for (int i = 0; i < 10; i++) {
            TestCase testCase = new TestCase();
            testCase.init();
            testCase.select();
            testCase.end();
        }
    }
4745 3480 3198 3179 3157 3173 3159 3149 3160 3160 useServerPrepStmts=true&cachePrepStmts=true
5288 3797 3578 3553 3568 3596 3550 3541 3549 3540 
8835 7208 6840 6721 7008 7143 6756 6732 6810 6910 useServerPrepStmts=true
5559 4063 3963 3833 3756 3714 3639 3597 3549 3616 cachePrepStmts=true

  忽略每行的第一个数据(ps:不要问我为什么,我排除了数据库缓存,java缓存,jit优化,类加载。第一个还是最大的。。。谁知道原因告诉我下)
  可以看出两个参数都启用的情况下,sql执行效率还是有所提升的,但是幅度不是很大。
  但是为什么只启用useServerPrepStmts的情况下效率反倒降低了,负优化?这要从cachePrepStmts的作用说起了。
  cachePrepStmts的作用是在 ps.close();的时候将PreparedStatement 缓存到conn的map里,第二次prepare相同的sql的时候就命中缓存。在开启服务端预编译的情况下,同一个PreparedStatement 对象在执行execute的时候服务端不需要执行prepare,但是如果没有带上cachePrepStmts参数那就是每次都是新的PreparedStatement,服务端每次都要执行prepare。具体的可以自己动手看log和源码。

总结下

  1. jdbc用PreparedStatement就开启了本地的预编译功能,可以起到防止sql注入的效果
  2. 如果要提升sql执行效率,必须同时带上useServerPrepStmts=true&cachePrepStmts=true

实验环境:mysql-connector-java 5.1.39
实验数据:https://github.com/datacharmer/test_db.git

你可能感兴趣的:(Mysql预编译)