我试图在Ant中执行如下groovy sql选择
<target name="groovy_sql">
<groovy>
import groovy.sql.Sql
def sql = Sql.newInstance(properties."master.jdbc_connection_string", properties."master.database_user", properties."master.database_password", "net.sourceforge.jtds.jdbc.Driver")
def table = '['+properties."app.database_name"+']..FILE_DATA'
def row = sql.firstRow("SELECT top 1 id from ${table} order by id desc")
properties."fileDataId" = row[0]
</groovy>
<echo message="fileDataId: ${fileDataId}"/>
</target>
我得到以下错误
[groovy] Sep 04, 2015 2:16:14 PM groovy.sql.Sql$AbstractQueryCommand execute
[groovy] WARNING: Failed to execute: SELECT top 1 id from ? order by id desc because: Must declare the table variable "@P0".
我认为这个错误的原因是表名不能作为参数传递。由于这个脚本必须在不同的环境中运行,我们在不同的环境中有不同的模式,所以我不能硬编码模式名称,我很难找出解决方案。有人能帮我解决这个问题吗?
可以拆分字符串赋值。首先从项目中读取,然后连接。
下面是一个从命令行 获取属性的例子<?xml version="1.0"?>
<project name="demo" basedir="." default="demo">
<taskdef name="groovy"
classpath="${user.home}/.gvm/groovy/2.3.6/embeddable/groovy-all-2.3.6.jar"
classname="org.codehaus.groovy.ant.Groovy" />
<target name="demo">
<!-- can load all props from a file here-->
<property name="table" value="hardcoded"/>
<groovy>
<arg value="hello1"/>
<arg value="hello2"/>
<arg value="hello3"/>
println args[0]
println args[2]
println 'projectName:'+ project.name
println project.getProperty("table")
def var="SELECT top 1 id from " + project.properties["table"] + " order by id desc"
println var;
</groovy>
</target>
</project>
我没有sql环境来测试它,所以它只是打印。
下面显示了运行
的输出$ ant
demo:
[groovy] hello1
[groovy] hello3
[groovy] projectName:demo
[groovy] hardcoded
[groovy] SELECT top 1 id from hardcoded order by id desc
接受命令行参数
$ ant -Dtable=newtable
demo:
[groovy] hello1
[groovy] hello3
[groovy] projectName:demo
[groovy] newtable
[groovy] SELECT top 1 id from newtable order by id desc