2016-04-06 29 views
0

我使用這個:PreparedStatement不適用於substring_index?

PreparedStatement preStatement = conn.prepareStatement("SELECT * FROM SomeTable WHERE attributeId = ? AND substring_index(substring_index(rowIdCombo,',',2),',',-1) = ?"); 

preStatement.setString(1, anAttributeID.toString()); 
preStatement.setString(2, locationID.toString()); 

使用相同的查詢搜索MySQL的終端上正常工作。只有在Java中使用PreparedStatement時纔會發生這種情況。

rowIdCombo基本上是一串逗號分隔的數字。像這樣:23,56,64,3

返回的結果集爲空。我如何獲得此查詢的工作?

+0

是不是更容易在Java中分割rowIdCombo,並寫一個更乾淨的PreparedStatement?至少可讀性問題,也更容易調試。 – JDDelgado

+0

如果我不使用'substring_index',select *將返回200萬行,這將是一個問題,因爲我正在查詢服務器上的數據庫。我需要通過SQL本身找到子字符串,以便只返回少數必需的行。另外,因爲SQL遊標在返回大量行時不會持續很長時間。 – Nav

+0

等待,根據您的代碼,rowIdCombo被視爲字面rowIdCombo字符串,而不是實際值(23,56,64,2)。 – JDDelgado

回答

1

基於的

System.out.println(preStatement); 

其輸出是:

[email protected]: SELECT * FROM mydb.SomeTable WHERE attributeId = '6' AND substring_index(substring_index(rowIdCombo,',',2),',',-1) = '1'

和按您的評論,在更換= '1'= 1已經解決了問題,爲防止單引號包裝,請將PreparedStatement中的值設置爲整數,請使用:

preStatement.setInt(2, Integer.parseInt(locationID.toString())); 
+0

我剛剛發現的另一個解決方案是使用''SELECT * FROM SomeTable WHERE attributeId =?AND substring_index(substring_index(rowIdCombo,',',2),',', - 1)=「+ var +」;「'。 var是'String var = num.toString();' – Nav

+0

是的,這也可以,但是如果你的代碼應該是參賽者,那麼如果你使用PreparedStatement你需要繼續使用它:),再加上它比串聯 – Yazan

+0

使用串聯可以打開[SQL注入](http://www.w3schools.com/sql/sql_injection.asp)的方法。 –

相關問題