package com.bjpowernode.jdbc;import java.sql.*; /**处理查询结果集 提醒:JDBC中所有的下标都是从1开始的。*/ public class 处理查询结果集 {public static void main(String[] args){Connection conn = null;Statement stmt = null;ResultSet rs = null;try{//1、注册驱动DriverManager.registerDriver(new com.mysql.jdbc.Driver());//2、获取连接conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","******");//3、获取数据库操作对象stmt = conn.createStatement();//4、执行SQL语句String sql = "select empno,ename,sal from emp order by sal desc";//执行查询语句使用的方法是:executeQuery()//ResultSet rs就是查询结果集对象,查询的结果都在这个对象中。rs = stmt.executeQuery(sql);//5、处理查询结果集//目前没有什么好的处理方式,直接将查询结果集中的数据遍历输出/*ResultSet rs对象中有以下数据-----+--------+---------+| 7839 | KING | 5000.00 || 7788 | SCOTT | 3000.00 || 7902 | FORD | 3000.00 || 7566 | JONES | 2975.00 || 7698 | BLAKE | 2850.00 || 7782 | CLARK | 2450.00 || 7499 | ALLEN | 1600.00 || 7844 | TURNER | 1500.00 || 7934 | MILLER | 1300.00 || 7654 | MARTIN | 1250.00 || 7521 | WARD | 1250.00 || 7876 | ADAMS | 1100.00 || 7900 | JAMES | 950.00 || 7369 | SMITH | 800.00 |+-------+--------+---------+*///rs.next()命令是判断在结果集中的下一条记录是否有数据,有数据返回true,无数据返回false。while(rs.next()){ //根据下标来取值,并且不管底层数据库中的数据是什么类型,都是以String类型取出/*String empno = rs.getString(1);String ename = rs.getString(2);String sal = rs.getString(3);System.out.println(empno + "," + ename + "," + sal);*///根据下标来取值,以特定类型取出/*int empno = rs.getInt(1);String ename = rs.getString(2);double sal = rs.getDouble(3);System.out.println(empno + "," + ename + "," + sal);*///根据查询结果的"列名"也可以取出 这里是查询结果的列名,不是源数据库的字段名称//如果select语句中起了别名,那么这里就是那个别名。//以后这种方式是常用的,因为"健壮"。int empno = rs.getInt("empno");String ename = rs.getString("ename");double sal = rs.getDouble("sal");System.out.println(empno + "," + ename + "," + sal);}}catch(SQLException e){e.printStackTrace();}finally{//6、释放资源(需要注意释放的顺序:先rs、再stmt、最后conn)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();}}}} }