Groovy系列之基本语法——变量

本文介绍了Groovy编程语言中的变量声明,强调了变量命名的规则,包括变量名可以包含字母、数字和下划线,且需以字母或下划线开头,并指出Groovy是区分大小写的。此外,还讲解了如何使用println函数打印变量的值。

一、变量声明

问:变量声明是什么?

答:告诉编译器为变量创建存储的位置和大小。

class Example { 
   static void main(String[] args) { 
      // x is defined as a variable 
      String x = "Hello";
		
      // The value of the variable is printed to the console 
      println(x);
   }
}

运行结果如下:

Hello

二、 变量命名

变量的名称可以由字母、数字和下划线字符组成,必须以字母或下划线开头

大写和小写字母是不同的,因为Groovy就像Java一样,是一种区分大小写的编程语言

class Example { 
   static void main(String[] args) { 
      // Defining a variable in lowercase  
      int x = 5;
	  
      // Defining a variable in uppercase  
      int X = 6; 
	  
      // Defining a variable with the underscore in it's name 
      def _Name = "Joe"; 
		
      println(x); 
      println(X); 
      println(_Name); 
   } 
}

运行结果如下:

5 
6 
Joe 

注意:x和X是两个不同的变量,因为区分大小写,在第三种情况下,_Name以下划线开头。

三、打印变量

可以使用println函数打印变量的当前值。

class Example { 
   static void main(String[] args) { 
      //Initializing 2 variables 
      int x = 5; 
      int X = 6; 
	  
      //Printing the value of the variables to the console 
      println("The value of x is " + x + "The value of X is " + X);  
   }
}

运行结果如下:

The value of x is 5 The value of X is 6 
你提到这是 **Groovy 脚本**,那我们需要重新评估你的原始代码。以下是你的原始代码: ```groovy String str = "\"kyl\".KYL > 0 " if(customConditionKey){ if(customConditionKey.cid){ str += "AND \"kyl\".CID = \${cid, Long} " } if(customConditionKey.materialId){ str += "AND \"kyl\".GOOD IN {\${bomDetail, String} }" } } return str; ``` --- ### ❌ 答案:**语法不正确或严重误导性写法** 虽然 Groovy 支持字符串插值(如 `"Hello ${name}"`),但以下几点说明这段代码 **在标准 Groovy 中无法正常工作**,尤其在 SQL 构建上下文中。 --- ## 🔍 详细分析 ### 1. `${cid, Long}` 不是 Groovy 的合法语法 ```groovy "AND \"kyl\".CID = \${cid, Long}" ``` - Groovy 字符串插值只支持表达式:`"${cid}"` ✅ - 但 `"\${cid, Long}"` 是非法的!逗号 `,` 会导致语法错误 ❌ - 类型标注 `Long` 在字符串中无意义 —— Groovy 不会在运行时做类型转换通过这种写法。 > 这种写法更像是模仿了某些模板引擎(如 MyBatis、GStringTemplateEngine)的 DSL,但在普通 GString 中无效。 --- ### 2. `{${bomDetail, String}}` 同样非法 ```groovy "AND \"kyl\".GOOD IN {\${bomDetail, String} }" ``` - 大括号 `{}` 是普通字符,不会被解析为集合操作。 - `bomDetail` 应该是一个列表,但直接插入会调用 `.toString()`,结果可能是 `[A,B,C]`,而这不是 SQL 合法的 `IN` 子句格式。 - 最终可能生成: ```sql AND "kyl".GOOD IN {[A,B,C]} ``` → ❌ 语法错误,SQL 不识别 `[...]`。 --- ### 3. 缺少空格导致 SQL 错误 ```groovy str += "AND \"kyl\".CID = \${cid}" ``` 如果前面 `str` 结尾是空格不够,或者后续没有空格,容易拼出: ```sql KYL > 0AND "kyl".CID = ... ``` → ❌ 缺少空格,SQL 报错。 --- ## ✅ 正确做法(Groovy 安全构建动态 SQL) ### ✅ 方案一:使用参数化查询 + 占位符(推荐) 假设你在使用类似 SqlBuilder 或执行预编译语句的环境: ```groovy def conditions = ['"kyl".KYL > 0'] def params = [] if (customConditionKey) { if (customConditionKey.cid != null) { conditions << '"kyl".CID = ?' params << customConditionKey.cid } if (customConditionKey.materialId && customConditionKey.bomDetail) { def placeholders = customConditionKey.bomDetail.collect { '?' }.join(',') conditions << "\"kyl\".GOOD IN ($placeholders)" params.addAll(customConditionKey.bomDetail) } } def sql = conditions.join(' AND ') // 返回 SQL 和参数(供 PreparedStatement 使用) [sql: sql, params: params] ``` #### 示例输出: ```groovy sql: "kyl".KYL > 0 AND "kyl".CID = ? AND "kyl".GOOD IN (?,?) params: [123, 'M001', 'M002'] ``` 这样可以安全传递给 JDBC 或 ORM 框架。 --- ### ✅ 方案二:如果你真的想用模板引擎(如 `GStringTemplateEngine`) 你可以定义一个模板风格脚本: ```groovy import groovy.text.GStringTemplateEngine def binding = [ cid: 123, bomDetail: ['M001', 'M002'] ] def templateText = ''' "kyl".KYL > 0 <% if (cid) { %> AND "kyl".CID = ${cid} <% } %> <% if (bomDetail) { %> AND "kyl".GOOD IN (<%= bomDetail.collect{ "'${it}'" }.join(',') %>) <% } %> '''.stripIndent() def engine = new GStringTemplateEngine() def template = engine.createTemplate(templateText).make(binding) println template.toString().replaceAll(/\n+/, ' ').trim() ``` #### 输出: ```sql "kyl".KYL > 0 AND "kyl".CID = 123 AND "kyl".GOOD IN ('M001','M002') ``` ⚠️ 注意:这种方式仍然有注入风险,除非你确保 `bomDetail` 来自可信源。 --- ## ⚠️ 绝对禁止的做法(即使 Groovy 允许) ```groovy // 千万别这么干! str += "AND \"kyl\".CID = ${customConditionKey.cid}" ``` 如果 `cid` 是用户输入,这会导致 SQL 注入! --- ## ✅ 推荐结构(完整 Groovy 函数示例) ```groovy Map buildQuery(def customConditionKey) { def conditions = ['"kyl".KYL > 0'] def params = [] if (customConditionKey) { if (customConditionKey.cid != null) { conditions << '"kyl".CID = ?' params << customConditionKey.cid } if (customConditionKey.materialId && customConditionKey.bomDetail) { // 假设 bomDetail 是 List 或数组 def placeholders = ['?'] * customConditionKey.bomDetail.size() conditions << "\"kyl\".GOOD IN (${placeholders.join(',')})" params.addAll(customConditionKey.bomDetail) } } return [ sql: conditions.join(' AND '), params: params ] } ``` 调用方式: ```groovy def result = buildQuery(customConditionKey) println "SQL: ${result.sql}" println "Params: ${result.params}" ``` --- ## 总结 | 问题 | 是否正确 | 建议 | |------|----------|------| | `${cid, Long}` 写法 | ❌ 非法 Groovy 语法 | 使用 `"${cid}"` 或 `?` 占位符 | | 直接拼接变量进 SQL | ❌ 有注入风险 | 改用参数化查询 | | 使用 `IN {list}` | ❌ SQL 不识别 | 手动生成 `IN (?,?)` | | 字符串连接逻辑 | ⚠️ 可行但危险 | 推荐分离 SQL 与参数 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猿道

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值