package IO; import java.io.IOException; import java.sql.*; import java.util.ArrayList; import java.util.List; public class Demo { private static Statement DBUtils; public static void main(String[] args) throws IOException, SQLException { try{ Class.forName("com.mysql.cj.jdbc.Driver"); }catch (ClassNotFoundException cne){ cne.printStackTrace(); } List<UserEntity> list=new ArrayList<UserEntity>(); String dburl = "jdbc:mysql://127.0.0.1:3306/bjsxt?&useSSL=false&serverTimezone=UTC"; String sql = "SELECT * FROM dept"; try{ Connection conn = DriverManager.getConnection(dburl,"root","root"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { UserEntity ue = new UserEntity(); //吧數據庫里面的信息取出來放到實體類里面 ue.setDeptno(rs.getInt("deptno")); ue.setDname(rs.getString("dname")); ue.setLoc(rs.getString("loc")); //把取出的數據添加到list集合里面 list.add(ue); } }catch (SQLException se) { se.printStackTrace(); } for(UserEntity u:list){ System.out.println(u.getDeptno()+"---"+u.getDname()+"---"+u.getLoc()); } } } class UserEntity{ private int deptno; private String dname; private String loc; public int getDeptno() { return deptno; } public void setDeptno(int deptno) { this.deptno = deptno; } public String getDname() { return dname; } public void setDname(String dname) { this.dname = dname; } public String getLoc() { return loc; } public void setLoc(String loc) { this.loc = loc; } } 運行結果: 10---ACCOUNTING---NEW YORK 20---RESEARCH---DALLAS 30---SALES---CHICAGO 40---OPERATIONS---BOSTON
數據庫表數據: