JDBC查询数据
之前我们使用"PreparedStatement" 将 sql 先编译成指令, 在发送给数据库执行,
如果发送的是一条 sql 语句, 执行之后会将查询到数据返回,
查询到的数据会被封装到接口 "Resultset" 对象中返回,
要在程序中取得查询的数据就需要使用到 "ResultSet" 接口.
将数据封装到一个 "ResultSet" 接口对象中,该对象叫做结果集对象 (就是查询到的结果的集合)
ResultSet 接口的方法:
boolean next() throws SQLException
判断结果集中是否还有吓一跳数据, 指针往下移动就可以判断, 如果有数据返回 true, 否则返回 falser.
getString(2) : 取得结果集中的 String 类型的数据
getDate(3) : 取得结果集中的 Date 类型的数据
getInt(4) : 取得结果集中的 int 类型的数据
getDouble(5) : 取得结果集中的 double 类型的数据
Demo: 根据编号查询(7788)
注意: 在从 RrsultSet 中取得数据的时候要和查询的时候字段的顺序和类型对应起来
1 public class TestMysql { 2 //取得连接 3 private static Connection conn =ConnectionUitl.getConnection(); 4 5 public static void main(String[] args) { 6 selectEmpById(7788); 7 } 8 /** 9 * 根据编号查询 10 * @param empno 要查询的雇员编号 11 */ 12 public static void selectEmpById(Integer empno) { 13 String sql = "SELECT empno,ename,job,hiredate,sal,comm,mgr,deptno" 14 + " FROM emp" 15 + " WHERE empno=" +empno; 16 17 try { 18 PreparedStatement pst = conn.prepareStatement(sql); 19 //将查询到的数据封装到了 ResultSet 结果集合中 20 ResultSet rst = pst.executeQuery(); 21 //将查询的数据从结果集中取得 22 if (rst.next()) { 23 System.out.println("雇员编号: " + rst.getInt(1)); 24 System.out.println("雇员姓名: " + rst.getString(2)); 25 System.out.println("雇员职位: " + rst.getString(3)); 26 System.out.println("雇员薪资: " + rst.getDouble(5)); 27 System.out.println("雇员入职日期: " + rst.getDate(4)); 28 System.out.println("雇员领导编号: " + rst.getInt(7)); 29 System.out.println("雇员部门编号: " + rst.getInt(8)); 30 System.out.println("雇员佣金: " + rst.getDouble(6)); 31 } 32 } catch (SQLException e) { 33 e.printStackTrace(); 34 } finally { 35 ConnectionUitl.close(conn); 36 } 37 } 38 }
Demo: 根据条件查询 (查询薪资大于1000 的雇员信息)
1 public class TestMysql { 2 //取得连接 3 private static Connection conn =ConnectionUitl.getConnection(); 4 5 public static void main(String[] args) { 6 selectEmps(); 7 } 8 /** 9 * 根据条件查询 10 */ 11 public static void selectEmps() { 12 String sql = "SELECT empno,ename,job,hiredate,sal,comm,mgr,deptno" 13 + " FROM emp" 14 + " WHERE sal>1000"; 15 16 try { 17 PreparedStatement pst = conn.prepareStatement(sql); 18 //将查询到的数据封装到了 ResultSet 结果集合中 19 ResultSet rst = pst.executeQuery(); 20 //将查询的数据从结果集中取得 21 while (rst.next()) { 22 System.out.print("雇员编号: " + rst.getInt(1)); 23 System.out.print("雇员姓名: " + rst.getString(2)); 24 System.out.print("雇员职位: " + rst.getString(3)); 25 System.out.print("雇员薪资: " + rst.getDouble(5)); 26 System.out.print("雇员入职日期: " + rst.getDate(4)); 27 System.out.print("雇员领导编号: " + rst.getInt(7)); 28 System.out.print("雇员部门编号: " + rst.getInt(8)); 29 System.out.println("雇员佣金: " + rst.getDouble(6)); 30 } 31 } catch (SQLException e) { 32 e.printStackTrace(); 33 } finally { 34 ConnectionUitl.close(conn); 35 } 36 } 37 }