Jdbc查询表中信息,使用集合查询

Jdbc查询表中信息,使用集合查询

package jdbc;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @outhor liu
 * @dare 2020/2/26 15:42
 */
public class StudentQuery {
    public static void main(String[] args) {
        List<Student> list = new StudentQuery().findAll();
        System.out.println(list);
    }
    public List<Student> findAll(){
        Connection conn=null;
        Statement stmt=null;
        ResultSet rs=null;

        ArrayList<Student> list=null;
        try {
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            //创建连接
             conn = DriverManager.getConnection
                    ("jdbc:mysql:///test?serverTimezone=GMT%2B8", "root", "123456");
            //sql执行语句
            String sql = "select * from users.student";

            //获取sql执行
             stmt = conn.createStatement();
            //执行sql
             rs = stmt.executeQuery(sql);

            //封装集合
            list = new ArrayList<>();
            Student s=null;

            while (rs.next()){
            //获取数据类型
                int sid = rs.getInt("sid");
                String sname = rs.getString("sname");
                int sage = rs.getInt("sage");
                String ssex = rs.getString("ssex");
                String smajor = rs.getString("smajor");
                String sclass = rs.getString("sclass");

         //封装数据
                s=new Student();
                s.setSid(sid);
                s.setSname(sname);
                s.setSage(sage);
                s.setSsex(ssex);
                s.setSmajor(smajor);
                s.setSclass(sclass);
                 //添加到集合
                list.add(s);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }if(stmt != null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }


        return list;
    }
}

你可能感兴趣的:(Jdbc查询表中信息,使用集合查询)