1. 程式人生 > >循環獲取數據庫中的值,並存儲到集合中

循環獲取數據庫中的值,並存儲到集合中

red .exe class ring dst 集合 next 新的 result

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);
}
}

循環獲取數據庫中的值,並存儲到集合中