2017-09-02 108 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中的關鍵字。

這個簡單的更改沒有任何錯誤。感謝您的迴應。

相關問題