某些场景下, 需要批量执行某些 sql, 其中 sql 中表名或者字段名是变量。
原生sql中, 一般使用存储过程实现。 本工具为了满足此场景, 引入了 execBatch 批量操作。
说明
- SQL
-- 前置sql, 列出所有表名
show tables;
-- 单线程批量操作, 获取所有表的表结构
execBatch(show create table @tables);
```sql
-- 前置sql, 列出所有表名
show tables;
-- 多线程批量操作, 获取所有表的表结构, 如果单个任务失败不影响其他任务继续执行
execBatch(show create table @tables) ON concurrent=5 and ignore_error=true;
- 语法
execBatch(任意sql可以使用@变量名和${变量名}) [ON concurrent=5 and ignore_error=true and safe_params=(ip) and on_error_query=(select ‘${ip}查询失败’ as msg)];
- 参数 V:0.3.25
参数 | 必填 | 默认值 | 举例 | 说明 |
---|---|---|---|---|
concurrent | 否 | 1 | 5 | 并发数 |
ignore_error | 否 | false | true | 是否忽略异常继续执行其他任务 |
safe_params | 否 | - | ip | 允许不加引号引入sql的变量列表 |
on_error_query | 否 | - | select ‘${ip}查询失败’ as msg | 子任务失败时时执行的sql |
on_empty_query | 否 | - | select ‘${ip}查询为空’ as msg | 子任务为空时时执行的sql |
- 变量
允许使用 ${}, #{}, $@{} 变量, 他们没有区别, 忽略外层单引号 ( ${} 与 ‘${}’ 等效 ).
默认除了safe_params以外, 所有的值都会强制嵌套外层单引号吗, 且内部的单引号会转移成两个单引号. (xxx = what’s 则 ${xxx} = ‘what’’s’)
-- xxx = what's 则 ${xxx} = 'what''s'
-- 推荐使用 '${xxx}' 表示变量名, 比如:
execBatch(select '${xxx}' as a)
-- 执行: select 'what''s' as a
-- 以下写法等效
execBatch(select ${xxx} as a)
execBatch(select '#{xxx}' as a)
-- 执行: select 'what''s' as a
-- 如果在 mybatis 环境下使用, ${} 和 #{} 会被 mybatis处理并报错, 可用 '$@{xxx}' 作延迟变量
execBatch(select '$@{xxx}' as a)
-- 执行: select 'what''s' as a
-- 以下写入有单引号问题
-- xxx = what's
execBatch(select '${xxx} you name' as a)
-- 执行: select 'what''s' as a
-- 错误: select ''what''s'you name' as a 引号不配对
-- safe_params 可以是一个或多个值
execBatch(select '${xxx} you name' as a) on safe_params=aaa
execBatch(select '${xxx} you name' as a) on safe_params=(aaa, bbb)