文章目录
预编译
预编译的好处
Mysql数据库有预编译功能。什么是预编译功能呢?它有什么好处呢?
当客户发送一条SQL语句给服务器后,服务器总是需要校验SQL语句的语法格式是否正确,然后把SQL语句编译成可执行的函数,最后才是执行SQL语句。其中校验语法,和编译所花的时间可能比执行SQL语句花的时间还要多。
如果我们需要执行多次insert语句,但只是每次插入的值不同,MySQL服务器也是需要每次都去校验SQL语句的语法格式,以及编译,这就浪费了太多的时间。如果使用预编译功能,那么只对SQL语句进行一次语法校验和编译,之后更换变量的值会直接执行,所以效率要高。
MySQL界面执行预编译
MySQL执行预编译分为如三步:
执行预编译语句
例如:
prepare myfun from 'select * from t_book where bid=?'
- 设置变量,例如:
set @str='b1'
- 执行语句,例如:
execute myfun using @str
如果需要再次执行myfun,那么就不再需要第一步,即不需要再编译语句了:
- 设置变量,例如:
set @str='b2'
- 执行语句,例如:
execute myfun using @str
JDBC驱动执行预编译
使用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()