我創建了一個數據庫相關的應用程序。如何在sql查詢中傳遞逗號分隔的字符串值?
在這我創建簡單的數據庫,並從數據庫中獲取值使用在 SQL查詢。
我的問題是我有像「2,6,8,9,10」這樣的字符串。 首先我分割這個字符串並存儲在一個數組列表中。用逗號。 在這個數組列表之後,我用2,6,8,9,10這個逗號合併。
我做得很好。 我在查詢中使用這個字符串來從數據庫中獲取值。 我的查詢是
SELECT tm.icon,tm.topic_no,td.topic_id,td.name FROM topicmaster tm ,topicmaster_description td WHERE td.topic_id =tm.topic_id AND td.langid='3' AND tm.oraganisationid ='1' AND td.topic_id in(2,6,8,9,10);
這一點。
但是當我通過合併字符串它`看起來像一個
SELECT tm.icon,tm.topic_no,td.topic_id,td.name FROM topicmaster tm ,topicmaster_description td WHERE td.topic_id =tm.topic_id AND td.langid='3' AND tm.oraganisationid ='1' AND td.topic_id in('2,6,8,9,10');
,所以我不能在in
事業運行查詢,因爲不同的通價值。 在上面的查詢工作正常,因爲它s like a
in(2,6,8,9,10) in second it look like a
in('2,6,8,9,10') so what to do. how to remove this
'`from string?
首先,我將字符串分割
//getTopicFile ArrayList with
public ArrayList<String> getAssignTopicArrayList(String passString)
{
ArrayList<String> rtnArrayList=new ArrayList<String>();
try
{
StringTokenizer strTokens = new StringTokenizer(passString,",");
while (strTokens.hasMoreElements())
{
rtnArrayList.add(String.valueOf(strTokens.nextToken()));
}
} catch (Exception ex)
{
ex.printStackTrace();
System.err.println("Error in Fetch ArrayList-->"+ex.toString());
}
return rtnArrayList;
}
//getTopicFile ArrayList with
後,我在新字符串
genHelper.showErrorLog("Assign Topic-->"+chapterAssignTopicName);
ArrayList<String> getTopicList=genHelper.getAssignTopicArrayList(chapterAssignTopicName);
String passConcat = "";
for (int i = 0; i < getTopicList.size(); i++)
{
System.out.println("Topic List--->"+getTopicList.get(i));
if(getTopicList.size()==1)
{
passConcat=passConcat.concat(String.valueOf(getTopicList.get(i)));
}
else
{
if(getTopicList.size()-1 == i)
{
System.err.println("value if --> " + i);
passConcat=passConcat.concat(String.valueOf(getTopicList.get(i)));
}else {
System.err.println("value else--> " + i);
passConcat=passConcat.concat(String.valueOf(getTopicList.get(i)).concat(","));
}
}
}
genHelper.showErrorLog("PassConcat String-->"+passConcat);
合併的話,我有了新的字符串和查詢通過it`下面
String topicQuery="SELECT tm.icon,tm.topic_no,td.topic_id,td.name FROM topicmaster tm ,topicmaster_description td WHERE td.topic_id =tm.topic_id AND td.langid='"+LanguageActivity.languageId+"' AND tm.oraganisationid ='"+genHelper.loadPreferences(String.valueOf(R.string.sharePrefin_Login_organizationid))+"' AND td.topic_id in('"+passConcat+"')";
你能分享一下java代碼嗎? –
等一分鐘,我分享它 –
看看那篇文章http://stackoverflow.com/questions/178479/preparedstatement-in-clause-alternatives –