我尝试在mysql中的几个dbs中运行相同的查询:
def m='xxx'
def dbs = ['DB05DEC05','DB06DEC06','DB07DEC07','DB08DEC08','DB09DEC09','DB10DEC10']
def sql =Sql.newInstance("jdbc:mysql://localhost:3306", "root","", "org.gjt.mm.mysql.Driver")
dbs.each{
db-> sql.eachRow("select * from ${db}.mail where mid=$m", { println "\t$db ${it.mid}"} );
}
Run Code Online (Sandbox Code Playgroud)
这给出了一个错误:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''DBJAN05DEC05'.mail where mid='xxx'
Run Code Online (Sandbox Code Playgroud)
Groovy显然用引号做了一些自定义的东西,并要求你不要在sql中使用引号(注意mid = $ m,如果你使用mid ='$ m'它警告你不要使用引号).问题是,在第一个$我根本不知道需要报价,报价是问题...
在vista上的groovy 1.7.谢谢
编辑:我发现了一个类似的问题,但它没有一个公认的答案...... Groovy GString问题
问题是SQL查询方法看到GString及其嵌入的变量引用,并将每个引用转换为?在准备好的声明中.
所以:
sql.query("select * from table where col = ${value}")
Run Code Online (Sandbox Code Playgroud)
......相当于:
sql.query("select * from table where col = ?", [ value ])
Run Code Online (Sandbox Code Playgroud)
但是也:
sql.query("select * from ${db}.table where col = ${value}")
Run Code Online (Sandbox Code Playgroud)
相当于:
sql.query("select * from ?.table where col = ?", [ db, value ])
Run Code Online (Sandbox Code Playgroud)
...因为select语句无效,因此在DB层失败.
显而易见的解决方法是使用query()的显式预准备语句版本.
dbs.each{ db->
sql.eachRow("select * from ${db}.mail where mid=?", m, {
println "\t$db ${it.mid}"
});
}
Run Code Online (Sandbox Code Playgroud)
但是,Sql类为您提供了一个expand()方法,它似乎是为此目的而设计的.
dbs.each{ db ->
sql.eachRow(
"select * from ${Sql.expand(db)}.mail where mid=${m}",
{ println "\t$db ${it.mid}"} );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1491 次 |
| 最近记录: |