🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# SqlTemplateClient的执行过程 示例代码: ~~~ sql_key_4_1 := "select.example.stpl" //模板文件名,SqlTemplate的key //执行的 sql:select * from user where id=7 //如部分参数未使用,请记得使用对应类型0值,如此处name参数值为空字符串,模板使用指南请详见pongo2 paramMap_4_1 := map[string]interface{}{"count": 2, "id": 7, "name": ""} results, err := engine.SqlTemplateClient(sql_key_4_1, &paramMap_4_1).Query().List() //执行的 sql:select * from user where name='xormplus' //如部分参数未使用,请记得使用对应类型0值,如此处id参数值为0,模板使用指南请详见pongo2 paramMap_4_2 := map[string]interface{}{"id": 0, "count": 0, "name": "xormplus"} results, err := engine.SqlTemplateClient(sql_key_4_1, &paramMap_4_2).Query().List() //执行的 sql:select * from user where name='xormplus' sql_key_7_1 := "select.example.stpl" //配置文件名,SqlTemplate的key var users []User paramMap_7_1 := map[string]interface{}{"id": 0, "count": 0, "name": "xormplus"} err := engine.SqlTemplateClient(sql_key_7_1, &paramMap_7_1).Find(&users) ~~~ 示例SQL模板: ~~~ select * from user where {% if count>1%} id=?id {% else%} name=?name {% endif %} ~~~ 过程说明: 1、SqlTemplateClient函数第二个参数存在时,则按约定需为*map[string]interface{}类型,该参数包含2部分内容,一部分为执行pongo2的SQL模板所需的执行参数,另一部分为通过执行pongo2的SQL模板获得的预编译SQL所需的sql参数。 2、SqlTemplateClient函数会执行pongo2的SQL模板获得的预编译SQL后,将map参数继续传递给后面的Query,Find,Search,Execute等函数继续执行预编译SQL。 3、以示例代码的第一部分为例,SqlTemplateClient函数,会依据传入的模板名称sql_key_4_1找到指定的执行SQL模板,依据传入的参数paramMap_4_1执行模板,获得预编译SQL为`select * from user where id=?`,之后将预编译SQL和paramMap_4_1传递给Query函数执行,最终执行的SQL为`select * from user where id=7` 4、最后请注意不要在SqlTemplate中硬拼接SQL,这样做存在SQL注入风险,请使用预编译SQL合理使用SqlTemplate。