这里以某id列为例:
public static String queryIdsBySql(String sql,String idName) throws Exception {
Connection conn=null;
PreparedStatement pstmt=null;
String resultIds=null;
try {
conn=getDBManager().getConnection();
pstmt=conn.prepareStatement(sql);
ResultSet rs=pstmt.executeQuery();
HashSet<Integer> hash=new HashSet<Integer>();
while(rs.next()){
int id = rs.getInt(idName);
hash.add(id);
}
Iterator ids=hash.iterator();
int i=1;
while(ids.hasNext()) {
if(i==1) {
resultIds=ids.next()+"";
i--;
}
resultIds=resultIds+","+ids.next();
}
}catch(Exception e) {
throw new Exception();
}finally {
try {
conn.close();
}catch(Exception e) {
e.printStackTrace();
}
}
return resultIds;
}
本文介绍了一种使用Java和SQL从数据库中查询特定ID并将其转换为逗号分隔字符串的方法。通过PreparedStatement执行SQL语句,利用HashSet存储查询到的ID,确保了ID的唯一性。最后,将HashSet中的ID遍历并转换成字符串形式返回。
385

被折叠的 条评论
为什么被折叠?



