zoukankan      html  css  js  c++  java
  • 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

    数据库表数据:

  • 相关阅读:
    【流水账】2021-06-19 Day-09
    【流水账】2021-06-18 Day-08
    【流水账】2021-06-16 Day-06
    【流水账】2021-06-15 Day-05
    .Net调用Java的实现方法
    优先队列的实例题
    栈的相关程序题
    重载函数
    卡特兰数
    关于全排列的递归
  • 原文地址:https://www.cnblogs.com/ibear/p/13532541.html
Copyright © 2011-2022 走看看