Convert string array into in condition of SQL and query with SQL

Time:2021-12-1

For example, I want to convert string [] STR = {“4”, “5”, “6”} into a string of “‘4 ‘,’ 5 ‘,’ 6 ‘”. In this way, I can use SQL query: select * from tablename ID in (string).

The source code implemented in the project is as follows:

Copy codeThe code is as follows:
StringBuffer idsStr = new StringBuffer();
for (int i = 0; i < ids.length; i++) {
if (i > 0) {
idsStr.append(“,”);
}
idsStr.append(“‘”).append(ids[i]).append(“‘”);
}

Another way I think of is as follows:

Copy codeThe code is as follows:
public static String stringArray2Strin(String[] str) {

StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length; i++) {
sb.append(“‘”).append(str[i]).append(“‘”).append(“,”);
}
return sb.toString().substring(0, sb.length() – 1);
}

public static void main(String[] args) {
String[] str = { “4”, “5”, “6” };
System.out.println(ItemGroupService.stringArray2String(str));
}