Groovy 连接到动态查询

Groovy concatenate to dynamic query

对 Groovy 有点陌生,我正在创建一段使用动态 sql 字符串执行 sql 查询的代码。

def executeQuery(String csvQueryInList) {
  def result = sql.rows('SELECT * FROM mySchema.myTable WHERE id IN (?,?)', ['1', '2'])
  return result
}

以上有效,但现在我想更改此代码以使用参数 csvQueryInList,它是一个 CSV 字符串。

像这样....

  def sqlStr = 'SELECT * FROM mySchema.myTable WHERE id IN ('
    def executeQuery(String queryInList) {

        def values = queryInList.tokenize(", ")
        values.eachWithIndex { item, index ->
            sqlStr << '?,'
        }
        sqlStr << ')'

        println "Executing generated query: $sqlStr"
        def result = sql.rows(sqlStr, values)
        return result
    }

但这并不完全奏效。

谁能帮助我纠正我的错误或提出更好的方法。

谢谢

我认为在构建带问号的查询时存在问题。

在这里您可以找到固定的,但有两点需要注意

  • 使用不传递 sqlStr 变量的方法。
  • 而不是 <<+ 可用于 连接

也更改了传递 sqlStr 的方法。

def sqlStr = 'SELECT * FROM mySchema.myTable WHERE id IN ('
def listStr =  '1,2 , 3, 50'

def executeQuery(String queryInList, String query){
        //Get the list values from the list
        def values = queryInList.split(',')*.trim()
        //Build the question marks string
        def listOfQuestions = values?.inject([]){ list, it -> list << '?';list }.join(',')
        query += listOfQuestions + ')'
        println "Executing generated query: $query"
        def result = sql.rows(query, values)
        return result
}
executeQuery(listStr, sqlStr)

您可以快速在线尝试此demo(仅查询建筑部分)。

希望以上内容有用。