为什么GroovySqlJDBCBuilder会发生此错误?
为什么此代码不获取sql.execute$y的字符串为什么GroovySqlJDBCBuilder会发生此错误?,sql,groovy,Sql,Groovy,为什么此代码不获取sql.execute$y的字符串 import groovy.sql.Sql def sql = Sql.newInstance("jdbc:mysql://localhost", "root","password", "com.mysql.jdbc.Driver") def y= "select * from table" table(sql,y) def table(sql,x){ println ("$x")
import groovy.sql.Sql
def sql = Sql.newInstance("jdbc:mysql://localhost", "root","password", "com.mysql.jdbc.Driver")
def y= "select * from table"
table(sql,y)
def table(sql,x){
println ("$x")
sql.execute("$x")
}
输出:
'select * from table'
Sep 02, 2017 3:49:39 PM groovy.sql.Sql$AbstractQueryCommand execute
WARNING: Failed to execute: ? because: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''select * from table'' at line 1
Caught: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''select * from table'' at line 1
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''select * from table'' at line 1
在groovy中,内部带有$expression的双引号字符串实际上是一个
因此,您正在调用此方法:
此方法将groovy字符串中的所有$表达式替换为
创建准备好的语句,并将所有$表达式作为此准备好的语句的参数传递
在你的情况下,x美元兑换成了什么?然后被处决
Mysql是否尝试解析此查询?并给出一个错误:
MySQLSyntaxErrorException: You have an error in your SQL syntax
如果将代码更改为:
sql.execute("$x" as String)
您将克服这个问题,但您将面临另一个问题:无法使用方法Sql.execute选择行
带参数的示例
以下命令是等效的:
def rows = sql.rows("select * from mytable where fieldA = $value")
def rows = sql.rows("select * from mytable where fieldA = ?", [value] )
def parms = [VALUE: value]
def rows = sql.rows(parms, "select * from mytable where fieldA = :VALUE")
所有这些都将作为准备好的语句select*from mytable执行,其中fieldA=?此问题通过如下所示的方法解决
import groovy.sql.Sql
def sql = Sql.newInstance("jdbc:mysql://localhost", "root","password", "com.mysql.jdbc.Driver")
def y= "select * from tablename"
table(sql,y)
def table(sql,x){
println (x)
sql.execute(x)
}
从表中选择*查询无法工作。因为表是sql中的关键字
这个简单的更改没有任何错误。感谢您的回复。双撇号在groovy中有宏替代,“single”notTABLE是一个保留字。。。需要进行分隔。MySQL使用背面标记。但是,更好的是,重新命名这个表。很抱歉我反应太晚了。我又犯了同样的错误。但我解释了为什么。。。你对代码做了任何修改吗?谢谢你的回复,兄弟。你完全正确。现在只有我意识到我错在哪里了。你的回答对我帮助很大。非常感谢。
import groovy.sql.Sql
def sql = Sql.newInstance("jdbc:mysql://localhost", "root","password", "com.mysql.jdbc.Driver")
def y= "select * from tablename"
table(sql,y)
def table(sql,x){
println (x)
sql.execute(x)
}