2017-09-02 119 views
0

为什么这段代码没有得到sql.execute(“$ y”)的字符串?为什么这个错误发生在groovy sql jdbc builder中?

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 
+0

“double”撇号在groovy中有宏指令,'single'not –

+0

TABLE是一个保留字...需要分隔。 (MySQL使用back-ticks。)但是,甚至更好,重命名表。 – jarlh

回答

1
sql.execute("$x") 

$expression常规双引号字符串其实里面是一个groovy.lang.GString

所以你调用此方法:Sql.execute(Gstring query)

这方法取代所有$expressions在常规字符串?

创建准备好的声明,并通过所有$expressions因为这事先准备好的声明

的参数,你的情况"$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 where fieldA = ?"

+0

对不起,我迟到的回应。我再次得到同样的错误。 –

+0

但我解释了为什么......你是否对代码做了任何修改? – daggett

+0

感谢您的回复。你完全正确。现在只有我意识到我犯了错误。你的回答非常有帮助。谢谢。 –

0

此问题通过以下所示的方法来解决被执行。

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) 
} 

"select * from table"查询无法正常工作。因为tablesql中的关键字。

这个简单的更改没有任何错误。感谢您的回应。

相关问题