用ResultSet接收数据并返回指定列的值

本文介绍了一种使用Java和SQL从数据库中查询特定ID并将其转换为逗号分隔字符串的方法。通过PreparedStatement执行SQL语句,利用HashSet存储查询到的ID,确保了ID的唯一性。最后,将HashSet中的ID遍历并转换成字符串形式返回。

这里以某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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值