这个驱动包的路径为
查询语句的处理:结果集指向表的开头的前一行,用next()方法指向下一行,如果为true说明有数据
获取各列的数据用get方法依次获取
也可以把某列的列号换位字段名
模拟前台和后台的交互
模拟后台处理结果,然后把处理结果放到List集合,让前台输出
后台代码
public static ListfindAll(){ Connection conn = null; Statement stmt = null; ResultSet rs=null; List list=new ArrayList(); try { String driver = "com.mysql.cj.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true"; String user = "root"; String password = ""; //加载驱动 Class.forName(driver); //与数据库建立连接 conn = DriverManager.getConnection(url, user, password); //建立sql命令发送器 stmt = conn.createStatement(); //准备一个sql命令,并用sql发送器发送过去,并返回结果 String sql = "select * from emp"; rs = stmt.executeQuery(sql); //处理结果(将JDBC的内容放到List集合中) while(rs.next()){ //获取当前行各个字段的值 int empno = rs.getInt("empno"); String name= rs.getString("ename"); String job = rs.getString("job"); int mgr = rs.getInt("mgr"); Date hireDate= rs.getDate("hiredate"); double sal = rs.getDouble("sal"); double comm = rs.getDouble("comm"); int deptno = rs.getInt("deptno"); //将当前行各个字段的值封装到Emp对象中 Emp emp = new Emp(empno,name,job,mgr,hireDate,sal,comm,deptno); //将Emp对象添加到集合 list.add(emp); } } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { //释放资源 try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return list; }
前台代码
public static void main(String[] args) throws Exception{
//调用后台并输出结果
List list=findAll();
//在前台输出结果
System.out.println("编号t姓名t岗位t上级编号t入职时间t薪水t补助t所属部门编号t");
for(Emp emp:list){
System.out.println(emp.getEmpno()+"t"+emp.getName()+"t"+emp.getJob()+"t"+emp.getMgr()+
"t"+emp.getHireDate()+"t"+emp.getSal()+"t"+emp.getComm()+"t"+emp.getDeptno());
}
}



