tansci-boot/magic-script-skill/references/sql-param.md

126 lines
2.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# SQL参数
## #{} 注入参数
作用和`mybatis`一致,都是将`#{}`区域替换为占位符`?`
```javascript
var id = 123;
return db.select("""
select * from sys_user where id = #{id}
""");
// 运行时生成的SQL为select * from sys_user where id = ?
```
此方法可以避免`sql`注入。
## ${} 拼接参数
作用和`mybatis`一致,都是将`${}`区域替换为对应的字符串
```javascript
var id = 123;
return db.select("""
select * from sys_user where id = ${id}
""");
// 运行时生成的SQL为select * from sys_user where id = 123
```
## 动态SQL参数
通过`?{condition,expression}`来实现动态拼接`SQL`
```javascript
return db.select("select * from sys_user ?{id,where id = #{id}}");
// 当id有值时,生成SQLselect * from sys_user where id = ?
// 当id无值时,生成SQLselect * from sys_user
return db.select("select * from sys_user ?{id!=null&&id.length() > 3,where id = #{id}}");
```
## 循环拼接参数
两种办法:
### in语法自动展开
```javascript
var ids = [1,2,3,4,5,6];
//会自动变成select * from sys_user where id in(?,?,?,?,?,?)
return db.select('select * from sys_user where id in(#{ids})');
```
### 循环拼接SQL
```javascript
var list = [1,2,3,4,5];
var sql = "select * from sys_user where ";
for(index,item in list){
sql = sql + 'id = #{list['+index+']}';
if(index + 1 < list.size()){
sql = sql + ' or ';
}
}
return db.select(sql);
```
## Mybatis语法支持
### 支持的关键字
- `<if>`
- `<elseif>`
- `<else>`
- `<where>`
- `<foreach>`
- `<trim>`
- `<set>`
### if
```javascript
var sql = """
select * from test_data
where 1 = 1
<if test="id != null">
and id = #{id}
</if>
"""
return db.select(sql)
```
### where
```javascript
var sql = """
select * from test_data
<where>
<if test="id != null">
and id = #{id}
</if>
</where>
"""
return db.select(sql)
```
### set、trim
```javascript
var sql = """
update test_data
<set>
<if test="name != null">
name = #{name}
</if>
<if test="content != null">
content = #{content}
</if>
</set>
where `id` = #{id}
"""
return db.update(sql)
```
### foreach
```javascript
var sql = """
select * from test_data
where id in
<foreach item='item' index='index' collection='body.ids'
open="(" separator="," close=")">
#{item}
</foreach>
"""
return db.select(sql)
```