Java獲取數據庫記錄通過javabean映射,並存入list集合


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

 

數據庫表數據:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM