dynamically set the db in a sql query

后端 未结 1 1841
天涯浪人
天涯浪人 2021-01-14 15:31

I try to run the same query in several dbs in mysql:

def m=\'xxx\'
def dbs =  [\'DB05DEC05\',\'DB06DEC06\',\'DB07DEC07\',\'DB08DEC08\',\'DB09DEC09\',\'DB10DE         


        
相关标签:
1条回答
  • 2021-01-14 16:13

    The problem is that the SQL query method sees the GString, with its embedded variable references, and turns each reference into a ? in a prepared statement.

    So:

    sql.query("select * from table where col = ${value}")
    

    ... is equivalent to:

    sql.query("select * from table where col = ?", [ value ])
    

    But also:

    sql.query("select * from ${db}.table where col = ${value}")
    

    is equivalent to:

    sql.query("select * from ?.table where col = ?", [ db, value ])
    

    ... which fails at the DB layer because the select statement is not valid.

    The obvious workaround is to use the explicit prepared statement version of query().

    dbs.each{ db-> 
        sql.eachRow("select * from ${db}.mail where mid=?", m, { 
           println "\t$db ${it.mid}"
        });
    }
    

    However, the Sql class gives you an expand() method, that appears to be designed for this purpose.

    dbs.each{ db -> 
       sql.eachRow(
          "select * from ${Sql.expand(db)}.mail where mid=${m}", 
          { println "\t$db ${it.mid}"} );
    }
    
    0 讨论(0)
提交回复
热议问题