-
标准SQL语言是一种__非过程性__的数据库操作语言,不能实现控制流程、函数、子程序。
因此,各个数据库软件都进行了扩展
-
过程的类型
(1) 批处理
将一个或多个SQL语句作为一组,从应用程序发送到数据库服务器。每组将会编译为单个可执行单元
MySQL添加批处理:在连接数据库URL时,设置参数rewriteBatchedStatements = true,另外还要使用addBatch和executeBatch
示例
public class Solution { private static String driverName = "com.mysql.jdbc.Driver"; private static String jdbcURL = "jdbc:mysql://localhost:3306/temp?rewriteBatchedStatements=true"; private static String databaseUserName = "acba"; private static String databasePassword = "123456"; private static String sql = "INSERT INTO temp VALUES (?, ?)"; public static void main(String[] args) { Connection connection = null; try { Class.forName(driverName); connection = DriverManager.getConnection(jdbcURL, databaseUserName, databasePassword); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(sql); // 插入10000条数据 for (int i = 0; i < 10000; i++) { preparedStatement.setInt(1, i); preparedStatement.setString(2, String.valueOf(i) + "_bc"); preparedStatement.addBatch(); } long startTime = System.currentTimeMillis(); preparedStatement.executeBatch(); long endTime = System.currentTimeMillis(); System.out.println((endTime - startTime)/1000.0); } catch (SQLException e) { e.printStackTrace(); } } }实测的结果是,添加了rewriteBatchedStatements = true之后,需要的时间约为0.1秒;不添加大概需要23秒
(2) 存储过程和触发器
(3) 脚本
编写一个.sql文件,然后用mysql自带的Workbench导入执行
chapter12_数据库编程_1_综述
本文探讨了标准SQL语言的非过程性特性及其在数据库操作中的局限性,介绍了通过批处理来提高SQL语句执行效率的方法,特别是MySQL中rewriteBatchedStatements参数的使用,以及如何通过示例代码实现10000条数据的批量插入,对比了开启和关闭批处理功能时的性能差异。

被折叠的 条评论
为什么被折叠?



