循环获取数据库中的值,并存储到集合中

package com.zdy.getxxx;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashSet;
import java.util.Set;


public class TestStudent {
public static void main(String[] args) {
try {
link();
} catch (Exception e) {
e.printStackTrace();
}
}

private static void link() throws Exception {

Connection conn = JdbcUtil.GetCon();
PreparedStatement pre = conn.prepareStatement("select * from student");

Set se = new HashSet();

ResultSet res = pre.executeQuery();

while (res.next()) {
       //每循环一次都会在内存中开辟一条新的空间
Student s = new Student();
s.setId(res.getInt("id"));
s.setSname(res.getString("sname"));
s.setSage(res.getInt("sage"));
s.setSsex(res.getBoolean("ssex"));
s.setSnumber(res.getInt("snumber"));
se.add(s);
}
System.out.println(se);
JdbcUtil.close(conn, pre, res);
}
}
posted @ 2019-04-02 20:32  若久  阅读(985)  评论(0编辑  收藏  举报