我必须在DB上执行查询,因为传递的值之一是我使用的数组StringUtils.join(array, "','")
以下是我实现它的方法,此代码是Web服务的服务器端的一部分
public String medico(int age, String sexstr, String etniastr, String[] sintom) {
String tes=StringUtils.join(sintom, "','");
String ris = "no";
String q;
String errore = connetti();
try {
if (errore.equals("")) {
Statement st = conn.createStatement();
//ESECUZIONE QUERY
q = "SELECT DISTINCT nome FROM malattia WHERE eta='" + age + "' AND sesso='" + sexstr + "' AND etnia='" + etniastr + "' AND sintomi IN('tes')";
ResultSet rs = st.executeQuery(q);
if (!rs.last()) {
ris = "no";
} else {
ris = "si";
}
} else {
ris = errore;
}
conn.close();
} catch (Exception e) {
ris = e.toString();
}
return ris;
}
我通过 tes 的方式似乎是问题所在,当我按照写入的方式传递它时,我将其更改为错误500(内部服务器错误):
..... sintomi IN('"+tes+"')";
它给我零行,即使数据库中存在相应的数据
解决此问题的正确方法是什么?提前谢谢。
答案 0 :(得分:3)
private String MEDICO_SQL = "SELECT DISTINCT nome FROM malattia WHERE eta=? AND sesso=? AND etnia=? AND sintomi IN (%s)";
public String medico(int age, String sexstr, String etniastr, String[] sintom) {
try {
String sql = String.format(MEDICO_SQL, StringUtils.repeat("?", ",", sintom.length));
PreparedStatement st = conn.prepareStatement(sql);
st.setInteger(1, age);
st.setString(2, sexstr);
st.setString(3, etniastr);
for (int i=0; i<sintom.length; i++) {
st.setString(3+i, sintom[i]);
}
ResultSet rs = s.executeQuery();
... process results ...
} catch (....) {
... handle exceptions ...
}
}
我假设你使用的StringUtils
是Apache Commons。
答案 1 :(得分:-1)
问题是除了逗号之外,你必须在开头和结尾添加单引号。
看看这个:
@Test
public void testArray() {
String[] strArray = {"hello", "world", "bye"};
System.out.println(singleQuoteAndComma(strArray));
}
private String singleQuoteAndComma(String[] strArray) {
String in = "";
for (int i = 0; i < strArray.length ; i++) {
in += "'" + strArray[i] + "'";
if (i != strArray.length - 1) {
in += ",";
}
}
return in;
}
输出:
'hello','world','bye'
使用singleQuoteAndComma方法,然后将结果字符串附加到查询中。
我做了更正:
public String medico(int age, String sexstr, String etniastr, String[] sintom) {
String tes= singleQuoteAndComma(sintom);
String ris = "no";
String q;
String errore = connetti();
try {
if (errore.equals("")) {
Statement st = conn.createStatement();
//ESECUZIONE QUERY
q = "SELECT DISTINCT nome FROM malattia WHERE eta='" + age + "' AND sesso='" + sexstr + "' AND etnia='" + etniastr + "' AND sintomi IN(" + tes + ")";
ResultSet rs = st.executeQuery(q);
if (!rs.last()) {
ris = "no";
} else {
ris = "si";
}
} else {
ris = errore;
}
conn.close();
} catch (Exception e) {
ris = e.toString();
}
return ris;
}