# 增删改查

## SQL参数

### #{} 注入参数
作用和`mybatis`一致，都是将`#{}`区域替换为占位符`?`
```javascript
var id = 123;
return db.select("""
    select * from sys_user where id = #{id}
""");
// 运行时生成的SQL为：select * from sys_user where id = ?
```

### ${} 拼接参数
作用和`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有值时,生成SQL：select * from sys_user where id = ?
// 当id无值时,生成SQL：select * from sys_user
```

## 切换数据源
```javascript
// 从数据源key定义为slave的库中查询
return db.slave.select("""
    select * from sys_user
""")
```

## SQL缓存
```javascript
// 将查询结果缓存到名为user_cache的缓存中，有效期1小时
return db.cache("user_cache", 3600 * 1000).select("""
    select * from sys_user
""")
```

## 使用事务

### 自动事务
```javascript
var val = db.transaction(()=>{
    var v1 = db.update('...');
    var v2 = db.update('....');
    return v2;
});
return val;
```

### 手动事务
```javascript
var tx = db.transaction();  //开启事务
try{
    var value = db.update('...');
    tx.commit();    // 提交事务
    return value;
}catch(e){
    tx.rollback();  // 回滚事务
}
```

## Mybatis语法支持

### 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>
    </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)
```
