將 String[] ids = {"4","5","6"} 轉為 '4','5','6',供 WHERE id IN (...) 使用。
StringBuffer idsStr = new StringBuffer();
for (int i = 0; i < ids.length; i++) {
if (i > 0) idsStr.append(",");
idsStr.append("'").append(ids[i]).append("'");
}
// 結果:'4','5','6'
public static String stringArrayToSqlIn(String[] arr) {
if (arr == null || arr.length == 0) return "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
sb.append("'").append(arr[i]).append("'");
if (i < arr.length - 1) sb.append(",");
}
return sb.toString();
}
// 測試
public static void main(String[] args) {
String[] str = {"4", "5", "6"};
System.out.println(stringArrayToSqlIn(str)); // '4','5','6'
}
直接拼接字串構建 SQL 極易導致 SQL 注入。生產環境務必使用參數化查詢:
// 正確做法:PreparedStatement + 動態佔位符
String placeholders = String.join(",", Collections.nCopies(ids.length, "?"));
String sql = "SELECT * FROM table WHERE id IN (" + placeholders + ")";
PreparedStatement ps = conn.prepareStatement(sql);
for (int i = 0; i < ids.length; i++) ps.setString(i+1, ids[i]);