我创建了一个数据库相关的应用程序。如何在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 –