JDBC高级编程 DAO

1 实现将某一个部门(Dept)的员工(Emp)工资的提升

本案例的详细要求如下:

1.如果职位(job)为“ANALYST”的员工,那么工资提升20%。

2.如果职位(job)为“MANAGER”的员工,那么工资提升30%。

3. 要求某部门下的以上两个职位的员工工资,要么工资全部提升成功,要么工资全部提升失败。

参考答案

实现此案例需要按照如下步骤进行。

步骤一:准备JDBC操作数据库的基本代码

首先,在EmpDAO类中新建updateSalByDeptno方法,方法的声明如下所示:

  1. publicvoidupdateSalByDeptno(int deptno){}

该方法实现将部门编号为deptno的、职位为“ANALYST”和“MANAGER”的员工的工资进行提升。

然后,准备数据库连接的Connection对象、操作SQL语句的Statement对象并进行异常的处理,代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.PreparedStatement;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. publicclass EmpDAO {
  9.     publicstaticvoid main(String[] args) {
  10.         EmpDAO dao = new EmpDAO();
  11.         // dao.findSalByEname("CLARK");
  12.         // dao.findSalByEname("a' OR 'b'='b");
  13.         // dao.findSalByEname1("CLARK");
  14.         // dao.findSalByEname1("a' OR 'b'='b");
  15.     }
  16.     publicvoidupdateSalByDeptno(int deptno) {
  17.         Connection con = null;
  18.         Statement stmt = null;
  19.         try {
  20.             con = ConnectionSource.getConnection();
  21.             stmt = con.createStatement();
  22.         } catch (SQLException e) {
  23.             
  24.             System.out.println("数据库访问异常!");
  25.             thrownew RuntimeException(e);
  26.         } finally {
  27.             try {
  28.                 if (stmt != null) {
  29.                     stmt.close();
  30.                 }
  31.                 if (con != null) {
  32.                     con.close();
  33.                 }
  34.             } catch (SQLException e) {
  35.                 System.out.println("释放资源时发生异常");
  36.             }
  37.         }
  38.     }
  39.     publicvoid findSalByEname(String ename) {
  40.         ... ...
  41.     }
  42.     publicvoid findSalByEname1(String ename) {
  43.         ... ...
  44.     }
  45. }

步骤二:实现员工工资的提升

使用Connection的setAutoCommit方法、commit方法以及rollback方法来控制事务,以正确实现员工工资的提升,代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.PreparedStatement;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. publicclass EmpDAO {
  9.     publicstaticvoid main(String[] args) {
  10.         EmpDAO dao = new EmpDAO();
  11.         // dao.findSalByEname("CLARK");
  12.         // dao.findSalByEname("a' OR 'b'='b");
  13.         // dao.findSalByEname1("CLARK");
  14.         // dao.findSalByEname1("a' OR 'b'='b");
  15.     }
  16.     publicvoidupdateSalByDeptno(int deptno) {
  17.         Connection con = null;
  18.         Statement stmt = null;
  19.         try {
  20.             con = ConnectionSource.getConnection();
  21.             stmt = con.createStatement();
  22.             // 插入数据的SQL语句
  23.             String sql1 = "update emp set sal =sal*1.2" + " where deptno="
  24.                     + deptno + " and job='ANALYST'";
  25.             String sql2 = "update emp set sal =sal*1.3" + " where deptno="
  26.                     + deptno + " and job='MANAGER'";
  27.             // 关闭自动提交
  28.             con.setAutoCommit(false);
  29.             // 执行SQL语句
  30.             stmt.executeUpdate(sql1);
  31.             stmt.executeUpdate(sql2);
  32.             // 提交
  33.             con.commit();
  34.         } catch (SQLException e) {
  35.             try {
  36.                 con.rollback();
  37.             } catch (SQLException e1) {
  38.                 System.out.println("回滚事务异常!");
  39.                 throw new RuntimeException(e1);
  40.             }
  41.             System.out.println("数据库访问异常!");
  42.             thrownew RuntimeException(e);
  43.         } finally {
  44.             try {
  45.                 if (stmt != null) {
  46.                     stmt.close();
  47.                 }
  48.                 if (con != null) {
  49.                     con.close();
  50.                 }
  51.             } catch (SQLException e) {
  52.                 System.out.println("释放资源时发生异常");
  53.             }
  54.         }
  55.     }
  56.     publicvoid findSalByEname(String ename) {
  57.         ... ...
  58.     }
  59.     publicvoid findSalByEname1(String ename) {
  60.         ... ...
  61.     }
  62. }

步骤三:测试

在EmpDAO类的main方法中,调用updateSalByDeptno方法,代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.PreparedStatement;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. publicclass EmpDAO {
  9.     publicstaticvoid main(String[] args) {
  10.         EmpDAO dao = new EmpDAO();
  11.         // dao.findSalByEname("CLARK");
  12.         // dao.findSalByEname("a' OR 'b'='b");
  13.         // dao.findSalByEname1("CLARK");
  14.         // dao.findSalByEname1("a' OR 'b'='b");
  15.         // 员工工资提升
  16.          dao.updateSalByDeptno(20);
  17.     }
  18.     publicvoidupdateSalByDeptno(int deptno) {
  19.         Connection con = null;
  20.         Statement stmt = null;
  21.         try {
  22.             con = ConnectionSource.getConnection();
  23.             stmt = con.createStatement();
  24.             // 插入数据的SQL语句
  25.             String sql1 = "update emp set sal =sal*1.2" + " where deptno="
  26.                     + deptno + " and job='ANALYST'";
  27.             String sql2 = "update emp set sal =sal*1.3" + " where deptno="
  28.                     + deptno + " and job='MANAGER'";
  29.             // 关闭自动提交
  30.             con.setAutoCommit(false);
  31.             // 执行SQL语句
  32.             stmt.executeUpdate(sql1);
  33.             stmt.executeUpdate(sql2);
  34.             // 提交
  35.             con.commit();
  36.         } catch (SQLException e) {
  37.             try {
  38.                 con.rollback();
  39.             } catch (SQLException e1) {
  40.                 System.out.println("回滚事务异常!");
  41.                 thrownew RuntimeException(e1);
  42.             }
  43.             System.out.println("数据库访问异常!");
  44.             thrownew RuntimeException(e);
  45.         } finally {
  46.             try {
  47.                 if (stmt != null) {
  48.                     stmt.close();
  49.                 }
  50.                 if (con != null) {
  51.                     con.close();
  52.                 }
  53.             } catch (SQLException e) {
  54.                 System.out.println("释放资源时发生异常");
  55.             }
  56.         }
  57.     }
  58.     publicvoid findSalByEname(String ename) {
  59.         ... ...
  60.     }
  61.     publicvoid findSalByEname1(String ename) {
  62.         ... ...
  63.     }
  64. }

运行EmpDAO类,然后查看Oracle数据库中的emp表,会发现部门编号为20的、职位为“ANALYST”和“MANAGER”的员工的工资进行了提升。

本案例中,类EmpDAO的完整代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.PreparedStatement;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. publicclass EmpDAO {
  9.     publicstaticvoid main(String[] args) {
  10.         EmpDAO dao = new EmpDAO();
  11.         // dao.findSalByEname("CLARK");
  12.         // dao.findSalByEname("a' OR 'b'='b");
  13.         // dao.findSalByEname1("CLARK");
  14.         // dao.findSalByEname1("a' OR 'b'='b");
  15.         // 事务管理
  16.         // dao.updateSalByDeptno(20);
  17.     }
  18.     publicvoid updateSalByDeptno(int deptno) {
  19.         Connection con = null;
  20.         Statement stmt = null;
  21.         try {
  22.             con = ConnectionSource.getConnection();
  23.             stmt = con.createStatement();
  24.             // 插入数据的SQL语句
  25.             String sql1 = "update emp set sal =sal*1.2" + " where deptno="
  26.                     + deptno + " and job='ANALYST'";
  27.             String sql2 = "update emp set sal =sal*1.3" + " where deptno="
  28.                     + deptno + " and job='MANAGER'";
  29.             // 关闭自动提交
  30.             con.setAutoCommit(false);
  31.             // 执行SQL语句
  32.             stmt.executeUpdate(sql1);
  33.             stmt.executeUpdate(sql2);
  34.             // 提交
  35.             con.commit();
  36.         } catch (SQLException e) {
  37.             try {
  38.                 con.rollback();
  39.             } catch (SQLException e1) {
  40.                 System.out.println("回滚事务异常!");
  41.                 thrownew RuntimeException(e1);
  42.             }
  43.             System.out.println("数据库访问异常!");
  44.             thrownew RuntimeException(e);
  45.         } finally {
  46.             try {
  47.                 if (stmt != null) {
  48.                     stmt.close();
  49.                 }
  50.                 if (con != null) {
  51.                     con.close();
  52.                 }
  53.             } catch (SQLException e) {
  54.                 System.out.println("释放资源时发生异常");
  55.             }
  56.         }
  57.     }
  58.     publicvoid findSalByEname(String ename) {
  59.         Connection con = null;
  60.         PreparedStatement stmt = null;
  61.         ResultSet rs = null;
  62.         String sql = null;
  63.         try {
  64.             sql = "select sal from emp where ename = ?";
  65.             con = ConnectionSource.getConnection();
  66.             stmt = con.prepareStatement(sql);
  67.             stmt.setString(1, ename);
  68.             rs = stmt.executeQuery();
  69.             while (rs.next()) {
  70.                 double sal = rs.getDouble("sal");
  71.                 System.out.println(sal);
  72.             }
  73.         } catch (SQLException e) {
  74.             System.out.println("数据库访问异常!");
  75.             thrownew RuntimeException(e);
  76.         } finally {
  77.             try {
  78.                 if (rs != null) {
  79.                     rs.close();
  80.                 }
  81.                 if (stmt != null) {
  82.                     stmt.close();
  83.                 }
  84.                 if (con != null) {
  85.                     con.close();
  86.                 }
  87.             } catch (SQLException e) {
  88.                 System.out.println("释放资源发生异常");
  89.             }
  90.         }
  91.     }
  92.     publicvoid findSalByEname1(String ename) {
  93.         Connection con = null;
  94.         Statement stmt = null;
  95.         ResultSet rs = null;
  96.         String sql = null;
  97.         try {
  98.             sql = "select sal from emp where ename = '" + ename + "'";
  99.             System.out.println(sql);
  100.             con = ConnectionSource.getConnection();
  101.             stmt = con.createStatement();
  102.             rs = stmt.executeQuery(sql);
  103.             while (rs.next()) {
  104.                 double sal = rs.getDouble("sal");
  105.                 System.out.println(sal);
  106.             }
  107.         } catch (SQLException e) {
  108.             System.out.println("数据库访问异常!");
  109.             thrownew RuntimeException(e);
  110.         } finally {
  111.             try {
  112.                 if (rs != null) {
  113.                     rs.close();
  114.                 }
  115.                 if (stmt != null) {
  116.                     stmt.close();
  117.                 }
  118.                 if (con != null) {
  119.                     con.close();
  120.                 }
  121.             } catch (SQLException e) {
  122.                 System.out.println("释放资源发生异常");
  123.             }
  124.         }
  125.     }
  126. }

db.properties文件的内容与之前案例一样没有变化,该文件完整内容如下所示:

 
  1. jdbc.driverClassName=oracle.jdbc.OracleDriver
  2. jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
  3. jdbc.username=scott
  4. jdbc.password=tiger
  5. #<!-- 初始化连接 -->
  6. dataSource.initialSize=10
  7. #<!-- 最大空闲连接 -->
  8. dataSource.maxIdle=20
  9. #<!-- 最小空闲连接 -->
  10. dataSource.minIdle=5
  11. #最大连接数量
  12. dataSource.maxActive=50
  13. #<!-- 超时等待时间以毫秒为单位 (6000毫秒/1000等于60秒 )-->
  14. dataSource.maxWait=1000

ConnectionSource类与之前案例一样没有变化,该类完整内容如下所示:

 
  1. import java.io.IOException;
  2. import java.sql.Connection;
  3. import java.sql.SQLException;
  4. import java.util.Properties;
  5. import org.apache.commons.dbcp.BasicDataSource;
  6. public class ConnectionSource {
  7.     private static BasicDataSource dataSource = null;
  8.     public ConnectionSource() {
  9.     }
  10.     public static void init() {
  11.         Properties dbProps = new Properties();
  12.         // 取配置文件可以根据实际的不同修改
  13.         try {
  14.             dbProps.load(ConnectionSource.class.getClassLoader().getResourceAsStream(
  15.                     "day01/v4/db.properties"));
  16.         } catch (IOException e) {
  17.             e.printStackTrace();
  18.         }
  19.         try {
  20.             String driveClassName = dbProps.getProperty("jdbc.driverClassName");
  21.             String url = dbProps.getProperty("jdbc.url");
  22.             String username = dbProps.getProperty("jdbc.username");
  23.             String password = dbProps.getProperty("jdbc.password");
  24.             String initialSize = dbProps.getProperty("dataSource.initialSize");
  25.             String minIdle = dbProps.getProperty("dataSource.minIdle");
  26.             String maxIdle = dbProps.getProperty("dataSource.maxIdle");
  27.             String maxWait = dbProps.getProperty("dataSource.maxWait");
  28.             String maxActive = dbProps.getProperty("dataSource.maxActive");
  29.             dataSource = new BasicDataSource();
  30.             dataSource.setDriverClassName(driveClassName);
  31.             dataSource.setUrl(url);
  32.             dataSource.setUsername(username);
  33.             dataSource.setPassword(password);
  34.             // 初始化连接数
  35.             if (initialSize != null)
  36.                 dataSource.setInitialSize(Integer.parseInt(initialSize));
  37.             // 最小空闲连接
  38.             if (minIdle != null)
  39.                 dataSource.setMinIdle(Integer.parseInt(minIdle));
  40.             // 最大空闲连接
  41.             if (maxIdle != null)
  42.                 dataSource.setMaxIdle(Integer.parseInt(maxIdle));
  43.             // 超时回收时间(以毫秒为单位)
  44.             if (maxWait != null)
  45.                 dataSource.setMaxWait(Long.parseLong(maxWait));
  46.             // 最大连接数
  47.             if (maxActive != null) {
  48.                 if (!maxActive.trim().equals("0"))
  49.                     dataSource.setMaxActive(Integer.parseInt(maxActive));
  50.             }
  51.         } catch (Exception e) {
  52.             e.printStackTrace();
  53.             System.out.println("创建连接池失败!请检查设置!!!");
  54.         }
  55.     }
  56.     public static synchronized Connection getConnection() throws SQLException {
  57.         if (dataSource == null) {
  58.             init();
  59.         }
  60.         Connection conn = null;
  61.         if (dataSource != null) {
  62.             conn = dataSource.getConnection();
  63.         }
  64.         return conn;
  65.     }
  66. }

2 批量插入Dept数据

向Dept表中批量插入100条数据,需要插入数据的列为deptno、dname,这两列的数据要求如下:

1. deptno列的数据通过序列dept_seq自动生成;

2. dname列的数据为字符串,格式为:“name”+循环次数i。

参考答案

实现此案例需要按照如下步骤进行。

步骤一:在Oracle数据库中创建序列dept_seq

在Oracle数据库中创建名为dept_seq的序列,该序列的起始值为1、步进为1,SQL语句如下所示:

 
  1. create sequence dept_seq start with 1 increment by 1;

步骤二:准备JDBC操作数据库的基本代码

首先,新建类Batch,在该类中新建batchAdd方法;然后,准备数据库连接Connection对象、操作SQL语句的Statement对象以及设置事务管理;最后进行异常的处理,代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.SQLException;
  3. import java.sql.Statement;
  4. import java.util.Random;
  5. publicclass Batch {
  6.     publicvoid batchAdd() {
  7.         Connection con = null;
  8.         Statement stmt = null;
  9.         String sql = null;
  10.         try {
  11.             con = ConnectionSource.getConnection();
  12.             stmt = con.createStatement();
  13.             // 关闭自动提交
  14.             con.setAutoCommit(false);
  15.             // 提交
  16.             con.commit();
  17.         } catch (SQLException e) {
  18.             System.out.println("数据库访问异常!");
  19.             thrownew RuntimeException(e);
  20.         } finally {
  21.             try {
  22.                 if (stmt != null) {
  23.                     stmt.close();
  24.                 }
  25.                 if (con != null) {
  26.                     con.close();
  27.                 }
  28.             } catch (SQLException e) {
  29.                 System.out.println("释放资源时发生异常");
  30.             }
  31.         }
  32.     }
  33.     publicstaticvoid main(String args[]) {
  34.     }
  35. }

步骤三:批量向Dept表中插入数据

使用Statement的addBatch方法和executeBatch方法,批量向Dept表中插入数据,代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.SQLException;
  3. import java.sql.Statement;
  4. import java.util.Random;
  5. publicclass Batch {
  6.     publicvoid batchAdd() {
  7.         Connection con = null;
  8.         Statement stmt = null;
  9.         String sql = null;
  10.         try {
  11.             con = ConnectionSource.getConnection();
  12.             stmt = con.createStatement();
  13.             // 关闭自动提交
  14.             con.setAutoCommit(false);
  15.             for (int i = 0; i < 100; i++) {
  16.                 // 插入数据的SQL语句
  17.                 sql = "insert into dept(deptno, dname, loc) values("
  18.                         + "dept_seq.nextval, 'name" + i + "', "
  19.                         + new Random().nextInt(10000) + ")";
  20.                 System.out.println(sql);
  21.                 // 将SQL语句加入到Batch中
  22.                 stmt.addBatch(sql);
  23.             }
  24.             // 执行批处理
  25.             stmt.executeBatch();
  26.             // 提交
  27.             con.commit();
  28.         } catch (SQLException e) {
  29.             System.out.println("数据库访问异常!");
  30.             thrownew RuntimeException(e);
  31.         } finally {
  32.             try {
  33.                 if (stmt != null) {
  34.                     stmt.close();
  35.                 }
  36.                 if (con != null) {
  37.                     con.close();
  38.                 }
  39.             } catch (SQLException e) {
  40.                 System.out.println("释放资源时发生异常");
  41.             }
  42.         }
  43.     }
  44.     publicstaticvoid main(String args[]) {
  45.     }
  46. }

步骤四:测试是否批量插入数据成功

在Batch类的main方法中,调用batchAdd方法,代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.SQLException;
  3. import java.sql.Statement;
  4. import java.util.Random;
  5. publicclass Batch {
  6.     publicvoid batchAdd() {
  7.         Connection con = null;
  8.         Statement stmt = null;
  9.         String sql = null;
  10.         try {
  11.             con = ConnectionSource.getConnection();
  12.             stmt = con.createStatement();
  13.             // 关闭自动提交
  14.             con.setAutoCommit(false);
  15.             for (int i = 0; i < 100; i++) {
  16.                 // 插入数据的SQL语句
  17.                 sql = "insert into dept(deptno, dname, loc) values("
  18.                         + "dept_seq.nextval, 'name" + i + "', "
  19.                         + new Random().nextInt(10000) + ")";
  20.                 System.out.println(sql);
  21.                 // 将SQL语句加入到Batch中
  22.                 stmt.addBatch(sql);
  23.             }
  24.             // 执行批处理
  25.             stmt.executeBatch();
  26.             // 提交
  27.             con.commit();
  28.         } catch (SQLException e) {
  29.             System.out.println("数据库访问异常!");
  30.             thrownew RuntimeException(e);
  31.         } finally {
  32.             try {
  33.                 if (stmt != null) {
  34.                     stmt.close();
  35.                 }
  36.                 if (con != null) {
  37.                     con.close();
  38.                 }
  39.             } catch (SQLException e) {
  40.                 System.out.println("释放资源时发生异常");
  41.             }
  42.         }
  43.     }
  44.     publicstaticvoid main(String args[]) {
  45.         Batch batch = new Batch();
  46.         batch.batchAdd();
  47.     }
  48. }

运行Batch类,然后去查看Oracle数据库中的Dept表,会发现批量向该表中插入了100条记录。

本案例中,Batch类的完整代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.SQLException;
  3. import java.sql.Statement;
  4. import java.util.Random;
  5. publicclass Batch {
  6.     publicvoid batchAdd() {
  7.         Connection con = null;
  8.         Statement stmt = null;
  9.         String sql = null;
  10.         try {
  11.             con = ConnectionSource.getConnection();
  12.             stmt = con.createStatement();
  13.             // 关闭自动提交
  14.             con.setAutoCommit(false);
  15.             for (int i = 0; i < 100; i++) {
  16.                 // 插入数据的SQL语句
  17.                 sql = "insert into dept(deptno, dname, loc) values("
  18.                         + "dept_seq.nextval, 'name" + i + "', "
  19.                         + new Random().nextInt(10000) + ")";
  20.                 System.out.println(sql);
  21.                 // 将SQL语句加入到Batch中
  22.                 stmt.addBatch(sql);
  23.             }
  24.             // 执行批处理
  25.             stmt.executeBatch();
  26.             // 提交
  27.             con.commit();
  28.         } catch (SQLException e) {
  29.             System.out.println("数据库访问异常!");
  30.             thrownew RuntimeException(e);
  31.         } finally {
  32.             try {
  33.                 if (stmt != null) {
  34.                     stmt.close();
  35.                 }
  36.                 if (con != null) {
  37.                     con.close();
  38.                 }
  39.             } catch (SQLException e) {
  40.                 System.out.println("释放资源时发生异常");
  41.             }
  42.         }
  43.     }
  44.     publicstaticvoid main(String args[]) {
  45.         Batch batch = new Batch();
  46.         batch.batchAdd();
  47.     }
  48. }

db.properties文件的内容与之前案例一样没有变化,该文件完整内容如下所示:

 
  1. jdbc.driverClassName=oracle.jdbc.OracleDriver
  2. jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
  3. jdbc.username=scott
  4. jdbc.password=tiger
  5. #<!-- 初始化连接 -->
  6. dataSource.initialSize=10
  7. #<!-- 最大空闲连接 -->
  8. dataSource.maxIdle=20
  9. #<!-- 最小空闲连接 -->
  10. dataSource.minIdle=5
  11. #最大连接数量
  12. dataSource.maxActive=50
  13. #<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
  14. dataSource.maxWait=1000

ConnectionSource类与之前案例一样没有变化,该类完整内容如下所示:

 
  1. import java.io.IOException;
  2. import java.sql.Connection;
  3. import java.sql.SQLException;
  4. import java.util.Properties;
  5. import org.apache.commons.dbcp.BasicDataSource;
  6. public class ConnectionSource {
  7.     private static BasicDataSource dataSource = null;
  8.     public ConnectionSource() {
  9.     }
  10.     public static void init() {
  11.         Properties dbProps = new Properties();
  12.         // 取配置文件可以根据实际的不同修改
  13.         try {
  14.             dbProps.load(ConnectionSource.class.getClassLoader().getResourceAsStream(
  15.                     "day01/v4/db.properties"));
  16.         } catch (IOException e) {
  17.             e.printStackTrace();
  18.         }
  19.         try {
  20.             String driveClassName = dbProps.getProperty("jdbc.driverClassName");
  21.             String url = dbProps.getProperty("jdbc.url");
  22.             String username = dbProps.getProperty("jdbc.username");
  23.             String password = dbProps.getProperty("jdbc.password");
  24.             String initialSize = dbProps.getProperty("dataSource.initialSize");
  25.             String minIdle = dbProps.getProperty("dataSource.minIdle");
  26.             String maxIdle = dbProps.getProperty("dataSource.maxIdle");
  27.             String maxWait = dbProps.getProperty("dataSource.maxWait");
  28.             String maxActive = dbProps.getProperty("dataSource.maxActive");
  29.             dataSource = new BasicDataSource();
  30.             dataSource.setDriverClassName(driveClassName);
  31.             dataSource.setUrl(url);
  32.             dataSource.setUsername(username);
  33.             dataSource.setPassword(password);
  34.             // 初始化连接数
  35.             if (initialSize != null)
  36.                 dataSource.setInitialSize(Integer.parseInt(initialSize));
  37.             // 最小空闲连接
  38.             if (minIdle != null)
  39.                 dataSource.setMinIdle(Integer.parseInt(minIdle));
  40.             // 最大空闲连接
  41.             if (maxIdle != null)
  42.                 dataSource.setMaxIdle(Integer.parseInt(maxIdle));
  43.             // 超时回收时间(以毫秒为单位)
  44.             if (maxWait != null)
  45.                 dataSource.setMaxWait(Long.parseLong(maxWait));
  46.             // 最大连接数
  47.             if (maxActive != null) {
  48.                 if (!maxActive.trim().equals("0"))
  49.                     dataSource.setMaxActive(Integer.parseInt(maxActive));
  50.             }
  51.         } catch (Exception e) {
  52.             e.printStackTrace();
  53.             System.out.println("创建连接池失败!请检查设置!!!");
  54.         }
  55.     }
  56.     public static synchronized Connection getConnection() throws SQLException {
  57.         if (dataSource == null) {
  58.             init();
  59.         }
  60.         Connection conn = null;
  61.         if (dataSource != null) {
  62.             conn = dataSource.getConnection();
  63.         }
  64.         return conn;
  65.     }
  66. }

3 向Emp表中插入一个团队成员

向Emp表中插入一个团队成员,该团队的成员信息如图-1所示。

图-1

从图-1可以看出tom为这个团队的管理者,其他三位员工的管理者ID(mgr) 都为1,而1是管理者tom的员工编号(empno)。

要求向Emp表插入以上四个员工的信息。职员marry、terry、jim的管理者ID(mgr)为刚刚插入Emp表的管理者tom的员工编号(empno)的数据。另外,Emp表的主键列empno的数据通过序列emp_seq获得。

参考答案

实现此案例需要按照如下步骤进行。

步骤一:创建序列emp_seq

在Oracle数据库中创建序列名为emp_seq,该序列的起始值为1、步进为1,SQL语句如下所示:

 
  1. create sequence emp_seq start with 1 increment by 1;

步骤二:创建Emp类

Emp类为实体类和数据表emp之间的映射,该类的代码如下所示:

 
  1. public class Emp {
  2.     private int empNo;
  3.     private String ename;
  4.     private String job;
  5.     private int mgr;
  6.     private String hiredate;
  7.     private double sal;
  8.     private double comm;
  9.     private int deptno;
  10.     
  11.     
  12.     
  13.     public Emp() {
  14.         super();
  15.     }
  16.     public Emp(int empNo, String ename, String job, int mgr, String hiredate,
  17.             double sal, double comm, int deptno) {
  18.         super();
  19.         this.empNo = empNo;
  20.         this.ename = ename;
  21.         this.job = job;
  22.         this.mgr = mgr;
  23.         this.hiredate = hiredate;
  24.         this.sal = sal;
  25.         this.comm = comm;
  26.         this.deptno = deptno;
  27.     }
  28.     public int getEmpNo() {
  29.         return empNo;
  30.     }
  31.     public void setEmpNo(int empNo) {
  32.         this.empNo = empNo;
  33.     }
  34.     public String getEname() {
  35.         return ename;
  36.     }
  37.     public void setEname(String ename) {
  38.         this.ename = ename;
  39.     }
  40.     public String getJob() {
  41.         return job;
  42.     }
  43.     public void setJob(String job) {
  44.         this.job = job;
  45.     }
  46.     public int getMgr() {
  47.         return mgr;
  48.     }
  49.     public void setMgr(int mgr) {
  50.         this.mgr = mgr;
  51.     }
  52.     public String getHiredate() {
  53.         return hiredate;
  54.     }
  55.     public void setHiredate(String hiredate) {
  56.         this.hiredate = hiredate;
  57.     }
  58.     public double getSal() {
  59.         return sal;
  60.     }
  61.     public void setSal(double sal) {
  62.         this.sal = sal;
  63.     }
  64.     public double getComm() {
  65.         return comm;
  66.     }
  67.     public void setComm(double comm) {
  68.         this.comm = comm;
  69.     }
  70.     public int getDeptno() {
  71.         return deptno;
  72.     }
  73.     public void setDeptno(int deptno) {
  74.         this.deptno = deptno;
  75.     }
  76. }

步骤三:准备JDBC操作数据库的基本代码

首先,在EmpDAO类中新建addTeam方法,该方法的声明如下:

  1.     publicvoid addTeam(List<Emp> emps)

该方法用于实现向Emp表插入一个团队的数据。其中参数emps表示该团队的所有员工,在集合emps中的索引为0的位置存储管理者,索引为1、2、3的位置存储该管理者下属的三名员工。

然后,准备数据库连接Connection对象、操作SQL语句的PreparedStatement对象以及设置事务管理;最后进行异常的处理,代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.PreparedStatement;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. publicclass EmpDAO {
  9.     publicstaticvoid main(String[] args) {
  10.         EmpDAO dao = new EmpDAO();
  11.         // dao.findSalByEname("CLARK");
  12.         // dao.findSalByEname("a' OR 'b'='b");
  13.         // dao.findSalByEname1("CLARK");
  14.         // dao.findSalByEname1("a' OR 'b'='b");
  15.         // 事务管理
  16.         // dao.updateSalByDeptno(20);
  17.         
  18.     }
  19.     publicvoid addTeam(List<Emp> emps) {
  20.         Connection con = null;
  21.         PreparedStatement stmt = null;
  22.         ResultSet rs = null;
  23.         String sql = null;
  24.         try {
  25.             con = ConnectionSource.getConnection();
  26.             // 关闭自动提交
  27.             con.setAutoCommit(false);
  28.             
  29.             con.commit();
  30.         } catch (SQLException e) {
  31.             System.out.println("数据库访问异常!");
  32.             thrownew RuntimeException(e);
  33.         } finally {
  34.             try {
  35.                 if (rs != null) {
  36.                     rs.close();
  37.                 }
  38.                 if (stmt != null) {
  39.                     stmt.close();
  40.                 }
  41.                 if (con != null) {
  42.                     con.close();
  43.                 }
  44.             } catch (SQLException e) {
  45.                 System.out.println("释放资源时发生异常");
  46.             }
  47.         }
  48.     }
  49.     publicvoid updateSalByDeptno(int deptno) {
  50.         ... ...
  51.     }
  52.     publicvoid findSalByEname(String ename) {
  53.         ... ...
  54.     }
  55.     publicvoid findSalByEname1(String ename) {
  56.         ... ...
  57.     }
  58. }

步骤四:实现向Emp表中插入一个团队

向Emp表中插入数据,并使用PreparedStatement的getGeneratedKeys方法获得刚刚生成的主键,代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.PreparedStatement;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. publicclass EmpDAO {
  9.     publicstaticvoid main(String[] args) {
  10.         EmpDAO dao = new EmpDAO();
  11.         // dao.findSalByEname("CLARK");
  12.         // dao.findSalByEname("a' OR 'b'='b");
  13.         // dao.findSalByEname1("CLARK");
  14.         // dao.findSalByEname1("a' OR 'b'='b");
  15.         // 事务管理
  16.         // dao.updateSalByDeptno(20);
  17.     
  18.     }
  19.     publicvoid addTeam(List<Emp> emps) {
  20.         Connection con = null;
  21.         PreparedStatement stmt = null;
  22.         ResultSet rs = null;
  23.         String sql = null;
  24.         try {
  25.             con = ConnectionSource.getConnection();
  26.             // 关闭自动提交
  27.             con.setAutoCommit(false);
  28.         
  29.             sql = "insert into emp(empno, ename, job, mgr, hiredate, sal, comm, deptno)"
  30.                     + " values(emp_seq.nextval,?,?,?,to_date(?,'yyyy-mm-dd'),?,?,?)";
  31.             stmt = con.prepareStatement(sql, new String[] { "empno" });
  32.             int mgr = 0;
  33.             for (int i = 0; i < emps.size(); i++) {
  34.                 Emp emp = (Emp) emps.get(i);
  35.                 stmt.setString(1, emp.getEname());
  36.                 stmt.setString(2, emp.getJob());
  37.                 if (i == 0) {
  38.                     stmt.setInt(3, emp.getMgr());
  39.                 } else {
  40.                     stmt.setInt(3, mgr);
  41.                 }
  42.                 stmt.setString(4, emp.getHiredate());
  43.                 stmt.setDouble(5, emp.getSal());
  44.                 stmt.setDouble(6, emp.getComm());
  45.                 stmt.setInt(7, emp.getDeptno());
  46.                 stmt.executeUpdate();
  47.                 if (i == 0) {
  48.                     rs = stmt.getGeneratedKeys();
  49.                     if (rs.next()) {
  50.                         mgr = rs.getInt(1);
  51.                     }
  52.                 }
  53.             }
  54.             con.commit();
  55.         } catch (SQLException e) {
  56.             System.out.println("数据库访问异常!");
  57.             thrownew RuntimeException(e);
  58.         } finally {
  59.             try {
  60.                 if (rs != null) {
  61.                     rs.close();
  62.                 }
  63.                 if (stmt != null) {
  64.                     stmt.close();
  65.                 }
  66.                 if (con != null) {
  67.                     con.close();
  68.                 }
  69.             } catch (SQLException e) {
  70.                 System.out.println("释放资源时发生异常");
  71.             }
  72.         }
  73.     }
  74.     publicvoid updateSalByDeptno(int deptno) {
  75.         ... ...
  76.     }
  77.     publicvoid findSalByEname(String ename) {
  78.         ... ...
  79.     }
  80.     publicvoid findSalByEname1(String ename) {
  81.         ... ...
  82.     }
  83. }

步骤五:测试

按照图-1所示的数据构造四个Emp对象,并将这四个对象按照步骤三所描述的顺序存储到List集合中;然后将List集合对象作为参数传递给addTeam方法,代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.PreparedStatement;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. publicclass EmpDAO {
  9.     publicstaticvoid main(String[] args) {
  10.         EmpDAO dao = new EmpDAO();
  11.         // dao.findSalByEname("CLARK");
  12.         // dao.findSalByEname("a' OR 'b'='b");
  13.         // dao.findSalByEname1("CLARK");
  14.         // dao.findSalByEname1("a' OR 'b'='b");
  15.         // 事务管理
  16.         // dao.updateSalByDeptno(20);
  17.         // 将管理者放置在索引为0的位置
  18.         List<Emp> emps = new ArrayList<Emp>();
  19.         Emp emp1=new Emp();
  20.         emp1.setEname("tom");
  21.         emp1.setJob("manager");
  22.         emp1.setMgr(7839);
  23.         emp1.setHiredate("2014-05-01");
  24.         emp1.setSal(5000);
  25.         emp1.setComm(300);
  26.         emp1.setDeptno(30);
  27.         
  28.         Emp emp2=new Emp();
  29.         emp2.setEname("marry");
  30.         emp2.setJob("clerk");
  31.         emp2.setMgr(1);
  32.         emp2.setHiredate("2014-05-28");
  33.         emp2.setSal(2000);
  34.         emp2.setDeptno(30);
  35.         
  36.         Emp emp3=new Emp();
  37.         emp3.setEname("terry");
  38.         emp3.setJob("salesman");
  39.         emp3.setMgr(1);
  40.         emp3.setHiredate("2014-05-29");
  41.         emp3.setSal(2500);
  42.         emp3.setComm(200);
  43.         emp3.setDeptno(30);
  44.         
  45.         Emp emp4=new Emp();
  46.         emp4.setEname("jim");
  47.         emp4.setJob("salesman");
  48.         emp4.setMgr(1);
  49.         emp4.setHiredate("2014-05-26");
  50.         emp4.setSal(2500);
  51.         emp4.setComm(200);
  52.         emp4.setDeptno(30);
  53.     
  54.      emps.add(emp1);
  55.      emps.add(emp2);
  56.      emps.add(emp3);
  57.      emps.add(emp4);
  58.     
  59.         dao.addTeam(emps);
  60.     }
  61.     publicvoid addTeam(List<Emp> emps) {
  62.         Connection con = null;
  63.         PreparedStatement stmt = null;
  64.         ResultSet rs = null;
  65.         String sql = null;
  66.         try {
  67.             con = ConnectionSource.getConnection();
  68.             // 关闭自动提交
  69.             con.setAutoCommit(false);
  70.             // 插入主表
  71.             sql = "insert into emp(empno, ename, job, mgr, hiredate, sal, comm, deptno)"
  72.                     + " values(emp_seq.nextval,?,?,?,to_date(?,'yyyy-mm-dd'),?,?,?)";
  73.             stmt = con.prepareStatement(sql, new String[] { "empno" });
  74.             int mgr = 0;
  75.             for (int i = 0; i < emps.size(); i++) {
  76.                 Emp emp = (Emp) emps.get(i);
  77.                 stmt.setString(1, emp.getEname());
  78.                 stmt.setString(2, emp.getJob());
  79.                 if (i == 0) {
  80.                     stmt.setInt(3, emp.getMgr());
  81.                 } else {
  82.                     stmt.setInt(3, mgr);
  83.                 }
  84.                 stmt.setString(4, emp.getHiredate());
  85.                 stmt.setDouble(5, emp.getSal());
  86.                 stmt.setDouble(6, emp.getComm());
  87.                 stmt.setInt(7, emp.getDeptno());
  88.                 stmt.executeUpdate();
  89.                 if (i == 0) {
  90.                     rs = stmt.getGeneratedKeys();
  91.                     if (rs.next()) {
  92.                         mgr = rs.getInt(1);
  93.                     }
  94.                 }
  95.             }
  96.             con.commit();
  97.         } catch (SQLException e) {
  98.             System.out.println("数据库访问异常!");
  99.             thrownew RuntimeException(e);
  100.         } finally {
  101.             try {
  102.                 if (rs != null) {
  103.                     rs.close();
  104.                 }
  105.                 if (stmt != null) {
  106.                     stmt.close();
  107.                 }
  108.                 if (con != null) {
  109.                     con.close();
  110.                 }
  111.             } catch (SQLException e) {
  112.                 System.out.println("释放资源时发生异常");
  113.             }
  114.         }
  115.     }
  116.     publicvoid updateSalByDeptno(int deptno) {
  117.         ... ...
  118.     }
  119.     publicvoid findSalByEname(String ename) {
  120.         ... ...
  121.     }
  122.     publicvoid findSalByEname1(String ename) {
  123.         ... ...
  124.     }
  125. }

运行上述代码,向Emp表插入了四条记录。其中一条记录为管理者信息,如果管理者的员工ID为1,那个其余三条员工记录的管理者ID为1。

本案例中,Emp类的完整代码如下:

 
  1. public class Emp {
  2.     private int empNo;
  3.     private String ename;
  4.     private String job;
  5.     private int mgr;
  6.     private String hiredate;
  7.     private double sal;
  8.     private double comm;
  9.     private int deptno;
  10.     
  11.     
  12.     
  13.     public Emp() {
  14.         super();
  15.     }
  16.     public Emp(int empNo, String ename, String job, int mgr, String hiredate,
  17.             double sal, double comm, int deptno) {
  18.         super();
  19.         this.empNo = empNo;
  20.         this.ename = ename;
  21.         this.job = job;
  22.         this.mgr = mgr;
  23.         this.hiredate = hiredate;
  24.         this.sal = sal;
  25.         this.comm = comm;
  26.         this.deptno = deptno;
  27.     }
  28.     public int getEmpNo() {
  29.         return empNo;
  30.     }
  31.     public void setEmpNo(int empNo) {
  32.         this.empNo = empNo;
  33.     }
  34.     public String getEname() {
  35.         return ename;
  36.     }
  37.     public void setEname(String ename) {
  38.         this.ename = ename;
  39.     }
  40.     public String getJob() {
  41.         return job;
  42.     }
  43.     public void setJob(String job) {
  44.         this.job = job;
  45.     }
  46.     public int getMgr() {
  47.         return mgr;
  48.     }
  49.     public void setMgr(int mgr) {
  50.         this.mgr = mgr;
  51.     }
  52.     public String getHiredate() {
  53.         return hiredate;
  54.     }
  55.     public void setHiredate(String hiredate) {
  56.         this.hiredate = hiredate;
  57.     }
  58.     public double getSal() {
  59.         return sal;
  60.     }
  61.     public void setSal(double sal) {
  62.         this.sal = sal;
  63.     }
  64.     public double getComm() {
  65.         return comm;
  66.     }
  67.     public void setComm(double comm) {
  68.         this.comm = comm;
  69.     }
  70.     public int getDeptno() {
  71.         return deptno;
  72.     }
  73.     public void setDeptno(int deptno) {
  74.         this.deptno = deptno;
  75.     }
  76. }

EmpDAO类的完整代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.PreparedStatement;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. publicclass EmpDAO {
  9.     publicstaticvoid main(String[] args) {
  10.         EmpDAO dao = new EmpDAO();
  11.         // dao.findSalByEname("CLARK");
  12.         // dao.findSalByEname("a' OR 'b'='b");
  13.         // dao.findSalByEname1("CLARK");
  14.         // dao.findSalByEname1("a' OR 'b'='b");
  15.         // 事务管理
  16.         // dao.updateSalByDeptno(20);
  17.         // 将管理者放置在emps(0)位置
  18.         List<Emp> emps = new ArrayList<Emp>();
  19.         Emp emp1=new Emp();
  20.         emp1.setEname("tom");
  21.         emp1.setJob("manager");
  22.         emp1.setMgr(7839);
  23.         emp1.setHiredate("2014-05-01");
  24.         emp1.setSal(5000);
  25.         emp1.setComm(300);
  26.         emp1.setDeptno(30);
  27.         
  28.         Emp emp2=new Emp();
  29.         emp2.setEname("marry");
  30.         emp2.setJob("clerk");
  31.         emp2.setMgr(1);
  32.         emp2.setHiredate("2014-05-28");
  33.         emp2.setSal(2000);
  34.         emp2.setDeptno(30);
  35.         
  36.         Emp emp3=new Emp();
  37.         emp3.setEname("terry");
  38.         emp3.setJob("salesman");
  39.         emp3.setMgr(1);
  40.         emp3.setHiredate("2014-05-29");
  41.         emp3.setSal(2500);
  42.         emp3.setComm(200);
  43.         emp3.setDeptno(30);
  44.         
  45.         Emp emp4=new Emp();
  46.         emp4.setEname("jim");
  47.         emp4.setJob("salesman");
  48.         emp4.setMgr(1);
  49.         emp4.setHiredate("2014-05-26");
  50.         emp4.setSal(2500);
  51.         emp4.setComm(200);
  52.         emp4.setDeptno(30);
  53.     
  54.      emps.add(emp1);
  55.      emps.add(emp2);
  56.      emps.add(emp3);
  57.      emps.add(emp4);
  58.     
  59.         dao.addTeam(emps);
  60.     }
  61.     publicvoid addTeam(List<Emp> emps) {
  62.         Connection con = null;
  63.         PreparedStatement stmt = null;
  64.         ResultSet rs = null;
  65.         String sql = null;
  66.         try {
  67.             con = ConnectionSource.getConnection();
  68.             // 关闭自动提交
  69.             con.setAutoCommit(false);
  70.             // 插入主表
  71.             sql = "insert into emp(empno, ename, job, mgr, hiredate, sal, comm, deptno)"
  72.                     + " values(emp_seq.nextval,?,?,?,to_date(?,'yyyy-mm-dd'),?,?,?)";
  73.             stmt = con.prepareStatement(sql, new String[] { "empno" });
  74.             int mgr = 0;
  75.             for (int i = 0; i < emps.size(); i++) {
  76.                 Emp emp = (Emp) emps.get(i);
  77.                 stmt.setString(1, emp.getEname());
  78.                 stmt.setString(2, emp.getJob());
  79.                 if (i == 0) {
  80.                     stmt.setInt(3, emp.getMgr());
  81.                 } else {
  82.                     stmt.setInt(3, mgr);
  83.                 }
  84.                 stmt.setString(4, emp.getHiredate());
  85.                 stmt.setDouble(5, emp.getSal());
  86.                 stmt.setDouble(6, emp.getComm());
  87.                 stmt.setInt(7, emp.getDeptno());
  88.                 stmt.executeUpdate();
  89.                 if (i == 0) {
  90.                     rs = stmt.getGeneratedKeys();
  91.                     if (rs.next()) {
  92.                         mgr = rs.getInt(1);
  93.                     }
  94.                 }
  95.             }
  96.             con.commit();
  97.         } catch (SQLException e) {
  98.             System.out.println("数据库访问异常!");
  99.             thrownew RuntimeException(e);
  100.         } finally {
  101.             try {
  102.                 if (rs != null) {
  103.                     rs.close();
  104.                 }
  105.                 if (stmt != null) {
  106.                     stmt.close();
  107.                 }
  108.                 if (con != null) {
  109.                     con.close();
  110.                 }
  111.             } catch (SQLException e) {
  112.                 System.out.println("释放资源时发生异常");
  113.             }
  114.         }
  115.     }
  116.     publicvoid updateSalByDeptno(int deptno) {
  117.         Connection con = null;
  118.         Statement stmt = null;
  119.         try {
  120.             con = ConnectionSource.getConnection();
  121.             stmt = con.createStatement();
  122.             // 插入数据的SQL语句
  123.             String sql1 = "update emp set sal =sal*1.2" + " where deptno="
  124.                     + deptno + " and job='ANALYST'";
  125.             String sql2 = "update emp set sal =sal*1.3" + " where deptno="
  126.                     + deptno + " and job='MANAGER'";
  127.             // 关闭自动提交
  128.             con.setAutoCommit(false);
  129.             // 执行SQL语句
  130.             stmt.executeUpdate(sql1);
  131.             stmt.executeUpdate(sql2);
  132.             // 提交
  133.             con.commit();
  134.         } catch (SQLException e) {
  135.             try {
  136.                 con.rollback();
  137.             } catch (SQLException e1) {
  138.                 System.out.println("回滚事务异常!");
  139.                 thrownew RuntimeException(e1);
  140.             }
  141.             System.out.println("数据库访问异常!");
  142.             thrownew RuntimeException(e);
  143.         } finally {
  144.             try {
  145.                 if (stmt != null) {
  146.                     stmt.close();
  147.                 }
  148.                 if (con != null) {
  149.                     con.close();
  150.                 }
  151.             } catch (SQLException e) {
  152.                 System.out.println("释放资源时发生异常");
  153.             }
  154.         }
  155.     }
  156.     publicvoid findSalByEname(String ename) {
  157.         Connection con = null;
  158.         PreparedStatement stmt = null;
  159.         ResultSet rs = null;
  160.         String sql = null;
  161.         try {
  162.             sql = "select sal from emp where ename = ?";
  163.             con = ConnectionSource.getConnection();
  164.             stmt = con.prepareStatement(sql);
  165.             stmt.setString(1, ename);
  166.             rs = stmt.executeQuery();
  167.             while (rs.next()) {
  168.                 double sal = rs.getDouble("sal");
  169.                 System.out.println(sal);
  170.             }
  171.         } catch (SQLException e) {
  172.             System.out.println("数据库访问异常!");
  173.             thrownew RuntimeException(e);
  174.         } finally {
  175.             try {
  176.                 if (rs != null) {
  177.                     rs.close();
  178.                 }
  179.                 if (stmt != null) {
  180.                     stmt.close();
  181.                 }
  182.                 if (con != null) {
  183.                     con.close();
  184.                 }
  185.             } catch (SQLException e) {
  186.                 System.out.println("释放资源发生异常");
  187.             }
  188.         }
  189.     }
  190.     publicvoid findSalByEname1(String ename) {
  191.         Connection con = null;
  192.         Statement stmt = null;
  193.         ResultSet rs = null;
  194.         String sql = null;
  195.         try {
  196.             sql = "select sal from emp where ename = '" + ename + "'";
  197.             System.out.println(sql);
  198.             con = ConnectionSource.getConnection();
  199.             stmt = con.createStatement();
  200.             rs = stmt.executeQuery(sql);
  201.             while (rs.next()) {
  202.                 double sal = rs.getDouble("sal");
  203.                 System.out.println(sal);
  204.             }
  205.         } catch (SQLException e) {
  206.             System.out.println("数据库访问异常!");
  207.             thrownew RuntimeException(e);
  208.         } finally {
  209.             try {
  210.                 if (rs != null) {
  211.                     rs.close();
  212.                 }
  213.                 if (stmt != null) {
  214.                     stmt.close();
  215.                 }
  216.                 if (con != null) {
  217.                     con.close();
  218.                 }
  219.             } catch (SQLException e) {
  220.                 System.out.println("释放资源发生异常");
  221.             }
  222.         }
  223.     }
  224. }

db.properties文件的内容与之前案例一样没有变化,该文件完整内容如下所示:

 
  1. jdbc.driverClassName=oracle.jdbc.OracleDriver
  2. jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
  3. jdbc.username=scott
  4. jdbc.password=tiger
  5. #<!-- 初始化连接 -->
  6. dataSource.initialSize=10
  7. #<!-- 最大空闲连接 -->
  8. dataSource.maxIdle=20
  9. #<!-- 最小空闲连接 -->
  10. dataSource.minIdle=5
  11. #最大连接数量
  12. dataSource.maxActive=50
  13. #<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
  14. dataSource.maxWait=1000

ConnectionSource类与之前案例一样没有变化,该类完整内容如下所示:

 
  1. import java.io.IOException;
  2. import java.sql.Connection;
  3. import java.sql.SQLException;
  4. import java.util.Properties;
  5. import org.apache.commons.dbcp.BasicDataSource;
  6. public class ConnectionSource {
  7.     private static BasicDataSource dataSource = null;
  8.     public ConnectionSource() {
  9.     }
  10.     public static void init() {
  11.         Properties dbProps = new Properties();
  12.         // 取配置文件可以根据实际的不同修改
  13.         try {
  14.             dbProps.load(ConnectionSource.class.getClassLoader().getResourceAsStream(
  15.                     "day01/v4/db.properties"));
  16.         } catch (IOException e) {
  17.             e.printStackTrace();
  18.         }
  19.         try {
  20.             String driveClassName = dbProps.getProperty("jdbc.driverClassName");
  21.             String url = dbProps.getProperty("jdbc.url");
  22.             String username = dbProps.getProperty("jdbc.username");
  23.             String password = dbProps.getProperty("jdbc.password");
  24.             String initialSize = dbProps.getProperty("dataSource.initialSize");
  25.             String minIdle = dbProps.getProperty("dataSource.minIdle");
  26.             String maxIdle = dbProps.getProperty("dataSource.maxIdle");
  27.             String maxWait = dbProps.getProperty("dataSource.maxWait");
  28.             String maxActive = dbProps.getProperty("dataSource.maxActive");
  29.             dataSource = new BasicDataSource();
  30.             dataSource.setDriverClassName(driveClassName);
  31.             dataSource.setUrl(url);
  32.             dataSource.setUsername(username);
  33.             dataSource.setPassword(password);
  34.             // 初始化连接数
  35.             if (initialSize != null)
  36.                 dataSource.setInitialSize(Integer.parseInt(initialSize));
  37.             // 最小空闲连接
  38.             if (minIdle != null)
  39.                 dataSource.setMinIdle(Integer.parseInt(minIdle));
  40.             // 最大空闲连接
  41.             if (maxIdle != null)
  42.                 dataSource.setMaxIdle(Integer.parseInt(maxIdle));
  43.             // 超时回收时间(以毫秒为单位)
  44.             if (maxWait != null)
  45.                 dataSource.setMaxWait(Long.parseLong(maxWait));
  46.             // 最大连接数
  47.             if (maxActive != null) {
  48.                 if (!maxActive.trim().equals("0"))
  49.                     dataSource.setMaxActive(Integer.parseInt(maxActive));
  50.             }
  51.         } catch (Exception e) {
  52.             e.printStackTrace();
  53.             System.out.println("创建连接池失败!请检查设置!!!");
  54.         }
  55.     }
  56.     public static synchronized Connection getConnection() throws SQLException {
  57.         if (dataSource == null) {
  58.             init();
  59.         }
  60.         Connection conn = null;
  61.         if (dataSource != null) {
  62.             conn = dataSource.getConnection();
  63.         }
  64.         return conn;
  65.     }
  66. }

4 实现对Dept数据的分页查询(Oracle和MySQL)

使用JDBC分别连接Oracle数据库和MySQL数据库,实现对Dept表数据的分页查询功能。

参考答案

实现此案例需要按照如下步骤进行。

步骤一:添加方法findByPageOracle方法,并构建该方法的骨架代码

首先,在DeptDAO类中添加方法findByPageOracle,该方法的声明如下所示:

 
  1. publicvoid findByPageOracle(int page, int pageSize) {}

其中,参数page表示要查询的页码、参数pageSize表示每页显示的记录数。

然后,构建findByPageOracle方法的骨架代码,代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. publicclass DeptDAO {
  8.     publicstaticvoid main(String[] args) {
  9.         // 1.select
  10.         DeptDAO dao = new DeptDAO();
  11.         //dao.findAll();
  12.         // 2.insert
  13.         Dept dept = new Dept(50, "developer", "Beijing");
  14.         // dao.add(dept);
  15.         // 3.update
  16.         dept.setLoc("ShangHai");
  17.         //dao.update(dept);
  18.     }
  19.     /**
  20.      * @param page
  21.      * 要查看第几页
  22.      * @param pageSize
  23.      * 每页记录数
  24.      */
  25.     publicvoid findByPageOracle(int page, int pageSize) {
  26.         
  27.     }
  28.     publicvoid findAll() {
  29.         ... ...
  30.     }
  31.     publicvoid add(Dept dept) {
  32.         ... ...
  33.     }
  34.     publicvoid update(Dept dept) {
  35.         ... ...
  36.     }
  37. }

步骤二:定义SQL语句

在findByPageOracle方法中,定义变量sql_total以及sql来表示两条SQL语句,一条用于查询Emp表的总记录数,另一条作为分页的SQL语句,代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. publicclass DeptDAO {
  8.     publicstaticvoid main(String[] args) {
  9.         // 1.select
  10.         DeptDAO dao = new DeptDAO();
  11.         //dao.findAll();
  12.         // 2.insert
  13.         Dept dept = new Dept(50, "developer", "Beijing");
  14.         // dao.add(dept);
  15.         // 3.update
  16.         dept.setLoc("ShangHai");
  17.         //dao.update(dept);
  18.     }
  19.     /**
  20.      * @param page
  21.      * 要查看第几页
  22.      * @param pageSize
  23.      * 每页记录数
  24.      */
  25.     publicvoid findByPageOracle(int page, int pageSize) {
  26.         String sql_total = "select count(*) from dept";
  27.         String sql = "select * from "
  28.                 + "(select rownum rn, deptno, dname ,loc from "
  29.                 + "(select * from dept order by deptno) )"
  30.                 + " where rn between ? and ?";
  31.     }
  32.     publicvoid findAll() {
  33.         ... ...
  34.     }
  35.     publicvoid add(Dept dept) {
  36.         ... ...
  37.     }
  38.     publicvoid update(Dept dept) {
  39.         ... ...
  40.     }
  41. }

步骤三:查询Dept表的总记录数

获取数据库连接,使用PreparedStatement执行SQL语句(sql_total变量定义的SQL语句),获取数据库中Dept表的总记录数,代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. publicclass DeptDAO {
  8.     publicstaticvoid main(String[] args) {
  9.         // 1.select
  10.         DeptDAO dao = new DeptDAO();
  11.         //dao.findAll();
  12.         // 2.insert
  13.         Dept dept = new Dept(50, "developer", "Beijing");
  14.         // dao.add(dept);
  15.         // 3.update
  16.         dept.setLoc("ShangHai");
  17.         //dao.update(dept);
  18.     }
  19.     /**
  20.      * @param page
  21.      * 要查看第几页
  22.      * @param pageSize
  23.      * 每页记录数
  24.      */
  25.     publicvoid findByPageOracle(int page, int pageSize) {
  26.         Connection con = null;
  27.         PreparedStatement stmt = null;
  28.         ResultSet rs = null;
  29.         int total = -1;// 总记录数
  30.         String sql_total = "select count(*) from dept";
  31.         String sql = "select * from "
  32.                 + "(select rownum rn, deptno, dname ,loc from "
  33.                 + "(select * from dept order by deptno) )"
  34.                 + " where rn between ? and ?";
  35.         try {
  36.             con = ConnectionSource.getConnection();
  37.             stmt = con.prepareStatement(sql_total);
  38.             // 获得总的记录数
  39.             rs = stmt.executeQuery();
  40.             if (rs.next()) {
  41.                 total = rs.getInt(1);
  42.             }
  43.         } catch (SQLException e) {
  44.             System.out.println("数据库访问异常!");
  45.             thrownew RuntimeException(e);
  46.         } finally {
  47.             try {
  48.                 if (rs != null) {
  49.                     rs.close();
  50.                 }
  51.                 if (stmt != null) {
  52.                     stmt.close();
  53.                 }
  54.                 if (con != null) {
  55.                     con.close();
  56.                 }
  57.             } catch (SQLException e) {
  58.                 System.out.println("释放资源时发生异常");
  59.             }
  60.         }
  61.     }
  62.     publicvoid findAll() {
  63.         ... ...
  64.     }
  65.     publicvoid add(Dept dept) {
  66.         ... ...
  67.     }
  68.     publicvoid update(Dept dept) {
  69.         ... ...
  70.     }
  71. }

步骤四:计算总页数

将总记录数与每页记录数取余数,如果余数为0,则总页数等于总记录数除以每页记录数的商;如果余数不为0,则总页数等于总记录数除以每页记录数的商的基础上加1,代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. publicclass DeptDAO {
  8.     publicstaticvoid main(String[] args) {
  9.         // 1.select
  10.         DeptDAO dao = new DeptDAO();
  11.         //dao.findAll();
  12.         // 2.insert
  13.         Dept dept = new Dept(50, "developer", "Beijing");
  14.         // dao.add(dept);
  15.         // 3.update
  16.         dept.setLoc("ShangHai");
  17.         //dao.update(dept);
  18.     }
  19.     /**
  20.      * @param page
  21.      * 要查看第几页
  22.      * @param pageSize
  23.      * 每页记录数
  24.      */
  25.     publicvoid findByPageOracle(int page, int pageSize) {
  26.         Connection con = null;
  27.         PreparedStatement stmt = null;
  28.         ResultSet rs = null;
  29.         int total = -1;// 总记录数
  30.         int pages = -1;// 总页数
  31.         String sql_total = "select count(*) from dept";
  32.         String sql = "select * from "
  33.                 + "(select rownum rn, deptno, dname ,loc from "
  34.                 + "(select * from dept order by deptno) )"
  35.                 + " where rn between ? and ?";
  36.         try {
  37.             con = ConnectionSource.getConnection();
  38.             stmt = con.prepareStatement(sql_total);
  39.             // 获得总的记录数
  40.             rs = stmt.executeQuery();
  41.             if (rs.next()) {
  42.                 total = rs.getInt(1);
  43.             }
  44.             // 计算总共需要多少页
  45.             int mod = total % pageSize;
  46.             if (mod == 0)
  47.                 pages = total / pageSize;
  48.             else
  49.                 pages = total / pageSize + 1;
  50.         } catch (SQLException e) {
  51.             System.out.println("数据库访问异常!");
  52.             thrownew RuntimeException(e);
  53.         } finally {
  54.             try {
  55.                 if (rs != null) {
  56.                     rs.close();
  57.                 }
  58.                 if (stmt != null) {
  59.                     stmt.close();
  60.                 }
  61.                 if (con != null) {
  62.                     con.close();
  63.                 }
  64.             } catch (SQLException e) {
  65.                 System.out.println("释放资源时发生异常");
  66.             }
  67.         }
  68.     }
  69.     publicvoid findAll() {
  70.         ... ...
  71.     }
  72.     publicvoid add(Dept dept) {
  73.         ... ...
  74.     }
  75.     publicvoid update(Dept dept) {
  76.         ... ...
  77.     }
  78. }

步骤五:边界判断

如果要查看的页码大于总页数,则要查看的页码等于总页数;如果要查看的页码小于1,则要查看的页码等于1,代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. publicclass DeptDAO {
  8.     publicstaticvoid main(String[] args) {
  9.         // 1.select
  10.         DeptDAO dao = new DeptDAO();
  11.         //dao.findAll();
  12.         // 2.insert
  13.         Dept dept = new Dept(50, "developer", "Beijing");
  14.         // dao.add(dept);
  15.         // 3.update
  16.         dept.setLoc("ShangHai");
  17.         //dao.update(dept);
  18.     }
  19.     /**
  20.      * @param page
  21.      * 要查看第几页
  22.      * @param pageSize
  23.      * 每页记录数
  24.      */
  25.     publicvoid findByPageOracle(int page, int pageSize) {
  26.         Connection con = null;
  27.         PreparedStatement stmt = null;
  28.         ResultSet rs = null;
  29.         int total = -1;// 总记录数
  30.         int pages = -1;// 总页数
  31.         String sql_total = "select count(*) from dept";
  32.         String sql = "select * from "
  33.                 + "(select rownum rn, deptno, dname ,loc from "
  34.                 + "(select * from dept order by deptno) )"
  35.                 + " where rn between ? and ?";
  36.         try {
  37.             con = ConnectionSource.getConnection();
  38.             stmt = con.prepareStatement(sql_total);
  39.             // 获得总的记录数
  40.             rs = stmt.executeQuery();
  41.             if (rs.next()) {
  42.                 total = rs.getInt(1);
  43.             }
  44.             // 计算总共需要多少页
  45.             int mod = total % pageSize;
  46.             if (mod == 0)
  47.                 pages = total / pageSize;
  48.             else
  49.                 pages = total / pageSize + 1;
  50.             // 如果要查看的页数大于最大页,或者小于1,则取最后一页或第一页
  51.             if (page > pages)
  52.                 page = pages;
  53.             elseif (page < 1) {
  54.                 page = 1;
  55.             }
  56.         } catch (SQLException e) {
  57.             System.out.println("数据库访问异常!");
  58.             thrownew RuntimeException(e);
  59.         } finally {
  60.             try {
  61.                 if (rs != null) {
  62.                     rs.close();
  63.                 }
  64.                 if (stmt != null) {
  65.                     stmt.close();
  66.                 }
  67.                 if (con != null) {
  68.                     con.close();
  69.                 }
  70.             } catch (SQLException e) {
  71.                 System.out.println("释放资源时发生异常");
  72.             }
  73.         }
  74.     }
  75.     publicvoid findAll() {
  76.         ... ...
  77.     }
  78.     publicvoid add(Dept dept) {
  79.         ... ...
  80.     }
  81.     publicvoid update(Dept dept) {
  82.         ... ...
  83.     }
  84. }

步骤六:计算取记录的起始位置和结束位置

起始位置(begin)的计算公式如下:

 
  1. int begin = (page - 1) * pageSize + 1;

结束位置(end)的计算公式如下:

  1. int end = begin + pageSize - 1;

在findByPageOracle方法中的实现代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. publicclass DeptDAO {
  8.     publicstaticvoid main(String[] args) {
  9.         // 1.select
  10.         DeptDAO dao = new DeptDAO();
  11.         //dao.findAll();
  12.         // 2.insert
  13.         Dept dept = new Dept(50, "developer", "Beijing");
  14.         // dao.add(dept);
  15.         // 3.update
  16.         dept.setLoc("ShangHai");
  17.         //dao.update(dept);
  18.     }
  19.     /**
  20.      * @param page
  21.      * 要查看第几页
  22.      * @param pageSize
  23.      * 每页记录数
  24.      */
  25.     publicvoid findByPageOracle(int page, int pageSize) {
  26.         Connection con = null;
  27.         PreparedStatement stmt = null;
  28.         ResultSet rs = null;
  29.         int total = -1;// 总记录数
  30.         int pages = -1;// 总页数
  31.         String sql_total = "select count(*) from dept";
  32.         String sql = "select * from "
  33.                 + "(select rownum rn, deptno, dname ,loc from "
  34.                 + "(select * from dept order by deptno) )"
  35.                 + " where rn between ? and ?";
  36.         try {
  37.             con = ConnectionSource.getConnection();
  38.             stmt = con.prepareStatement(sql_total);
  39.             // 获得总的记录数
  40.             rs = stmt.executeQuery();
  41.             if (rs.next()) {
  42.                 total = rs.getInt(1);
  43.             }
  44.             // 计算总共需要多少页
  45.             int mod = total % pageSize;
  46.             if (mod == 0)
  47.                 pages = total / pageSize;
  48.             else
  49.                 pages = total / pageSize + 1;
  50.             // 如果要查看的页数大于最大页,或者小于1,则取最后一页或第一页
  51.             if (page > pages)
  52.                 page = pages;
  53.             elseif (page < 1) {
  54.                 page = 1;
  55.             }
  56.             int begin = (page - 1) * pageSize + 1;
  57.             int end = begin + pageSize - 1;
  58.         } catch (SQLException e) {
  59.             System.out.println("数据库访问异常!");
  60.             thrownew RuntimeException(e);
  61.         } finally {
  62.             try {
  63.                 if (rs != null) {
  64.                     rs.close();
  65.                 }
  66.                 if (stmt != null) {
  67.                     stmt.close();
  68.                 }
  69.                 if (con != null) {
  70.                     con.close();
  71.                 }
  72.             } catch (SQLException e) {
  73.                 System.out.println("释放资源时发生异常");
  74.             }
  75.         }
  76.     }
  77.     publicvoid findAll() {
  78.         ... ...
  79.     }
  80.     publicvoid add(Dept dept) {
  81.         ... ...
  82.     }
  83.     publicvoid update(Dept dept) {
  84.         ... ...
  85.     }
  86. }

步骤七:执行分页查询SQL语句

在findByPageOracle方法中执行分页查询的代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. publicclass DeptDAO {
  8.     publicstaticvoid main(String[] args) {
  9.         // 1.select
  10.         DeptDAO dao = new DeptDAO();
  11.         //dao.findAll();
  12.         // 2.insert
  13.         Dept dept = new Dept(50, "developer", "Beijing");
  14.         // dao.add(dept);
  15.         // 3.update
  16.         dept.setLoc("ShangHai");
  17.         //dao.update(dept);
  18.     }
  19.     /**
  20.      * @param page
  21.      * 要查看第几页
  22.      * @param pageSize
  23.      * 每页记录数
  24.      */
  25.     publicvoid findByPageOracle(int page, int pageSize) {
  26.         Connection con = null;
  27.         PreparedStatement stmt = null;
  28.         ResultSet rs = null;
  29.         int total = -1;// 总记录数
  30.         int pages = -1;// 总页数
  31.         String sql_total = "select count(*) from dept";
  32.         String sql = "select * from "
  33.                 + "(select rownum rn, deptno, dname ,loc from "
  34.                 + "(select * from dept order by deptno) )"
  35.                 + " where rn between ? and ?";
  36.         try {
  37.             con = ConnectionSource.getConnection();
  38.             stmt = con.prepareStatement(sql_total);
  39.             // 获得总的记录数
  40.             rs = stmt.executeQuery();
  41.             if (rs.next()) {
  42.                 total = rs.getInt(1);
  43.             }
  44.             // 计算总共需要多少页
  45.             int mod = total % pageSize;
  46.             if (mod == 0)
  47.                 pages = total / pageSize;
  48.             else
  49.                 pages = total / pageSize + 1;
  50.             // 如果要查看的页数大于最大页,或者小于1,则取最后一页或第一页
  51.             if (page > pages)
  52.                 page = pages;
  53.             elseif (page < 1) {
  54.                 page = 1;
  55.             }
  56.             int begin = (page - 1) * pageSize + 1;
  57.             int end = begin + pageSize - 1;
  58.             stmt = con.prepareStatement(sql);
  59.             stmt.setInt(1, begin);
  60.             stmt.setInt(2, end);
  61.             rs = stmt.executeQuery();
  62.             while (rs.next()) {
  63.                 System.out.println(rs.getInt("deptno") + ","
  64.                         + rs.getString("dname") + ","
  65.                         + rs.getString("loc"));
  66.             }
  67.         } catch (SQLException e) {
  68.             System.out.println("数据库访问异常!");
  69.             thrownew RuntimeException(e);
  70.         } finally {
  71.             try {
  72.                 if (rs != null) {
  73.                     rs.close();
  74.                 }
  75.                 if (stmt != null) {
  76.                     stmt.close();
  77.                 }
  78.                 if (con != null) {
  79.                     con.close();
  80.                 }
  81.             } catch (SQLException e) {
  82.                 System.out.println("释放资源时发生异常");
  83.             }
  84.         }
  85.     }
  86.     publicvoid findAll() {
  87.         ... ...
  88.     }
  89.     publicvoid add(Dept dept) {
  90.         ... ...
  91.     }
  92.     publicvoid update(Dept dept) {
  93.         ... ...
  94.     }
  95. }

步骤八:测试

在DeptDAO类的main方法中调用findByPageOracle方法,代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. publicclass DeptDAO {
  8.     publicstaticvoid main(String[] args) {
  9.         // 1.select
  10.         DeptDAO dao = new DeptDAO();
  11.         //dao.findAll();
  12.         // 2.insert
  13.         Dept dept = new Dept(50, "developer", "Beijing");
  14.         // dao.add(dept);
  15.         // 3.update
  16.         dept.setLoc("ShangHai");
  17.         //dao.update(dept);
  18.         // 4.findByPageOracle
  19.         dao.findByPageOracle(2, 3);// 查看第二页,每页3条
  20.     }
  21.     /**
  22.      * @param page
  23.      * 要查看第几页
  24.      * @param pageSize
  25.      * 每页记录数
  26.      */
  27.     publicvoid findByPageOracle(int page, int pageSize) {
  28.         Connection con = null;
  29.         PreparedStatement stmt = null;
  30.         ResultSet rs = null;
  31.         int total = -1;// 总记录数
  32.         int pages = -1;// 总页数
  33.         String sql_total = "select count(*) from dept";
  34.         String sql = "select * from "
  35.                 + "(select rownum rn, deptno, dname ,loc from "
  36.                 + "(select * from dept order by deptno) )"
  37.                 + " where rn between ? and ?";
  38.         try {
  39.             con = ConnectionSource.getConnection();
  40.             stmt = con.prepareStatement(sql_total);
  41.             // 获得总的记录数
  42.             rs = stmt.executeQuery();
  43.             if (rs.next()) {
  44.                 total = rs.getInt(1);
  45.             }
  46.             // 计算总共需要多少页
  47.             int mod = total % pageSize;
  48.             if (mod == 0)
  49.                 pages = total / pageSize;
  50.             else
  51.                 pages = total / pageSize + 1;
  52.             // 如果要查看的页数大于最大页,或者小于1,则取最后一页或第一页
  53.             if (page > pages)
  54.                 page = pages;
  55.             elseif (page < 1) {
  56.                 page = 1;
  57.             }
  58.             int begin = (page - 1) * pageSize + 1;
  59.             int end = begin + pageSize - 1;
  60.             stmt = con.prepareStatement(sql);
  61.             stmt.setInt(1, begin);
  62.             stmt.setInt(2, end);
  63.             rs = stmt.executeQuery();
  64.             while (rs.next()) {
  65.                 System.out.println(rs.getInt("deptno") + ","
  66.                         + rs.getString("dname") + ","
  67.                         + rs.getString("loc"));
  68.             }
  69.         } catch (SQLException e) {
  70.             System.out.println("数据库访问异常!");
  71.             thrownew RuntimeException(e);
  72.         } finally {
  73.             try {
  74.                 if (rs != null) {
  75.                     rs.close();
  76.                 }
  77.                 if (stmt != null) {
  78.                     stmt.close();
  79.                 }
  80.                 if (con != null) {
  81.                     con.close();
  82.                 }
  83.             } catch (SQLException e) {
  84.                 System.out.println("释放资源时发生异常");
  85.             }
  86.         }
  87.     }
  88.     publicvoid findAll() {
  89.         ... ...
  90.     }
  91.     publicvoid add(Dept dept) {
  92.         ... ...
  93.     }
  94.     publicvoid update(Dept dept) {
  95.         ... ...
  96.     }
  97. }

运行DeptDAO类,在控制台会输出第二页的三条数据。

步骤九:连接MySQL数据库,实现对Dept表中数据的分页查询

连接MySQL数据库,实现对Dept表中数据的分页查询,与连接Oracle是类似的。需要注意的是将db.properties文件中连接数据库的信息改为与MySQL数据库相关的,该文件内容如下:

  1. #jdbc.driverClassName=oracle.jdbc.OracleDriver
  2. #jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
  3. #jdbc.username=scott
  4. #jdbc.password=tiger
  5. jdbc.driverClassName=com.mysql.jdbc.Driver
  6. jdbc.url=jdbc:mysql://localhost:3306/tts7
  7. jdbc.username=root
  8. jdbc.password=root
  9. #<!-- 初始化连接 -->
  10. dataSource.initialSize=10
  11. #<!-- 最大空闲连接 -->
  12. dataSource.maxIdle=20
  13. #<!-- 最小空闲连接 -->
  14. dataSource.minIdle=5
  15. #最大连接数量
  16. dataSource.maxActive=50
  17. #<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
  18. dataSource.maxWait=1000

在DeptDAO类中添加findByPageMySQL方法,实现连接MySQL数据库,实现对Dept表中数据的分页查询,代码如下所示:

  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. publicclass DeptDAO {
  8.     publicstaticvoid main(String[] args) {
  9.         // 1.select
  10.         DeptDAO dao = new DeptDAO();
  11.         //dao.findAll();
  12.         // 2.insert
  13.         Dept dept = new Dept(50, "developer", "Beijing");
  14.         // dao.add(dept);
  15.         // 3.update
  16.         dept.setLoc("ShangHai");
  17.         //dao.update(dept);
  18.         // 4.findByPageOracle
  19.         //dao.findByPageOracle(2, 3);// 查看第二页,每页3条
  20.         // 5.findByPageMySQL
  21.         dao.findByPageMySQL(2, 3);// 查看第二页,每页3条
  22.     }
  23.     /**
  24.      * @param page
  25.      * 要查看第几页
  26.      * @param pageSize
  27.      * 每页记录数
  28.      */
  29.     publicvoid findByPageOracle(int page, int pageSize) {
  30.         Connection con = null;
  31.         PreparedStatement stmt = null;
  32.         ResultSet rs = null;
  33.         int total = -1;// 总记录数
  34.         int pages = -1;// 总页数
  35.         String sql_total = "select count(*) from dept";
  36.         String sql = "select * from "
  37.                 + "(select rownum rn, deptno, dname ,loc from "
  38.                 + "(select * from dept order by deptno) )"
  39.                 + " where rn between ? and ?";
  40.         try {
  41.             con = ConnectionSource.getConnection();
  42.             stmt = con.prepareStatement(sql_total);
  43.             // 获得总的记录数
  44.             rs = stmt.executeQuery();
  45.             if (rs.next()) {
  46.                 total = rs.getInt(1);
  47.             }
  48.             // 计算总共需要多少页
  49.             int mod = total % pageSize;
  50.             if (mod == 0)
  51.                 pages = total / pageSize;
  52.             else
  53.                 pages = total / pageSize + 1;
  54.             // 如果要查看的页数大于最大页,或者小于1,则取最后一页或第一页
  55.             if (page > pages)
  56.                 page = pages;
  57.             elseif (page < 1) {
  58.                 page = 1;
  59.             }
  60.             int begin = (page - 1) * pageSize + 1;
  61.             int end = begin + pageSize - 1;
  62.             stmt = con.prepareStatement(sql);
  63.             stmt.setInt(1, begin);
  64.             stmt.setInt(2, end);
  65.             rs = stmt.executeQuery();
  66.             while (rs.next()) {
  67.                 System.out.println(rs.getInt("deptno") + ","
  68.                         + rs.getString("dname") + ","
  69.                         + rs.getString("loc"));
  70.             }
  71.         } catch (SQLException e) {
  72.             System.out.println("数据库访问异常!");
  73.             thrownew RuntimeException(e);
  74.         } finally {
  75.             try {
  76.                 if (rs != null) {
  77.                     rs.close();
  78.                 }
  79.                 if (stmt != null) {
  80.                     stmt.close();
  81.                 }
  82.                 if (con != null) {
  83.                     con.close();
  84.                 }
  85.             } catch (SQLException e) {
  86.                 System.out.println("释放资源时发生异常");
  87.             }
  88.         }
  89.     }
  90.     /**
  91.      *
  92.      * @param page
  93.      * 要查看第几页
  94.      * @param pageSize
  95.      * 每页记录数
  96.      */
  97.     publicvoid findByPageMySQL(int page, int pageSize) {
  98.         Connection con = null;
  99.         PreparedStatement stmt = null;
  100.         ResultSet rs = null;
  101.         int total = -1;// 总记录数
  102.         int pages = -1;// 总页数
  103.         String sql_total = "select count(*) from dept";
  104.         String sql = "select * from dept order by deptno limit ?,?";
  105.         try {
  106.             con = ConnectionSource.getConnection();
  107.             stmt = con.prepareStatement(sql_total);
  108.             // 获得总的记录数
  109.             rs = stmt.executeQuery();
  110.             if (rs.next()) {
  111.                 total = rs.getInt(1);
  112.             }
  113.             System.out.println(total);
  114.             // 计算总共需要多少页
  115.             int mod = total % pageSize;
  116.             if (mod == 0)
  117.                 pages = total / pageSize;
  118.             else
  119.                 pages = total / pageSize + 1;
  120.             // 如果要查看的页数大于最大页,或者小于1,则取最后一页或第一页
  121.             if (page > pages)
  122.                 page = pages;
  123.             elseif (page < 1) {
  124.                 page = 1;
  125.             }
  126.             int start = (page - 1) * pageSize;
  127.             stmt = con.prepareStatement(sql);
  128.             stmt.setInt(1, start);
  129.             stmt.setInt(2, pageSize);
  130.             rs = stmt.executeQuery();
  131.             while (rs.next()) {
  132.                 System.out.println(rs.getInt("deptno") + ","
  133.                         + rs.getString("dname") + ","
  134.                         + rs.getString("loc"));
  135.             }
  136.         } catch (SQLException e) {
  137.             System.out.println("数据库访问异常!");
  138.             thrownew RuntimeException(e);
  139.         } finally {
  140.             try {
  141.                 if (rs != null) {
  142.                     rs.close();
  143.                 }
  144.                 if (stmt != null) {
  145.                     stmt.close();
  146.                 }
  147.                 if (con != null) {
  148.                     con.close();
  149.                 }
  150.             } catch (SQLException e) {
  151.                 System.out.println("释放资源时发生异常");
  152.             }
  153.         }
  154.     }
  155.     publicvoid findAll() {
  156.         ... ...
  157.     }
  158.     publicvoid add(Dept dept) {
  159.         ... ...
  160.     }
  161.     publicvoid update(Dept dept) {
  162.         ... ...
  163.     }
  164. }

本案例中,DeptDAO类的完整代码如下所示:

 
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. publicclass DeptDAO {
  8.     publicstaticvoid main(String[] args) {
  9.         // 1.select
  10.         DeptDAO dao = new DeptDAO();
  11.         //dao.findAll();
  12.         // 2.insert
  13.         Dept dept = new Dept(50, "developer", "Beijing");
  14.         // dao.add(dept);
  15.         // 3.update
  16.         dept.setLoc("ShangHai");
  17.         //dao.update(dept);
  18.         // 4.findByPageOracle
  19.         //dao.findByPageOracle(2, 3);// 查看第二页,每页3条
  20.         // 5.findByPageMySQL
  21.         dao.findByPageMySQL(2, 3);// 查看第二页,每页3条
  22.     }
  23.     /**
  24.      * @param page
  25.      * 要查看第几页
  26.      * @param pageSize
  27.      * 每页记录数
  28.      */
  29.     publicvoid findByPageOracle(int page, int pageSize) {
  30.         Connection con = null;
  31.         PreparedStatement stmt = null;
  32.         ResultSet rs = null;
  33.         int total = -1;// 总记录数
  34.         int pages = -1;// 总页数
  35.         String sql_total = "select count(*) from dept";
  36.         String sql = "select * from "
  37.                 + "(select rownum rn, deptno, dname ,loc from "
  38.                 + "(select * from dept order by deptno) )"
  39.                 + " where rn between ? and ?";
  40.         try {
  41.             con = ConnectionSource.getConnection();
  42.             stmt = con.prepareStatement(sql_total);
  43.             // 获得总的记录数
  44.             rs = stmt.executeQuery();
  45.             if (rs.next()) {
  46.                 total = rs.getInt(1);
  47.             }
  48.             // 计算总共需要多少页
  49.             int mod = total % pageSize;
  50.             if (mod == 0)
  51.                 pages = total / pageSize;
  52.             else
  53.                 pages = total / pageSize + 1;
  54.             // 如果要查看的页数大于最大页,或者小于1,则取最后一页或第一页
  55.             if (page > pages)
  56.                 page = pages;
  57.             elseif (page < 1) {
  58.                 page = 1;
  59.             }
  60.             int begin = (page - 1) * pageSize + 1;
  61.             int end = begin + pageSize - 1;
  62.             stmt = con.prepareStatement(sql);
  63.             stmt.setInt(1, begin);
  64.             stmt.setInt(2, end);
  65.             rs = stmt.executeQuery();
  66.             while (rs.next()) {
  67.                 System.out.println(rs.getInt("deptno") + ","
  68.                         + rs.getString("dname") + ","
  69.                         + rs.getString("loc"));
  70.             }
  71.         } catch (SQLException e) {
  72.             System.out.println("数据库访问异常!");
  73.             thrownew RuntimeException(e);
  74.         } finally {
  75.             try {
  76.                 if (rs != null) {
  77.                     rs.close();
  78.                 }
  79.                 if (stmt != null) {
  80.                     stmt.close();
  81.                 }
  82.                 if (con != null) {
  83.                     con.close();
  84.                 }
  85.             } catch (SQLException e) {
  86.                 System.out.println("释放资源时发生异常");
  87.             }
  88.         }
  89.     }
  90.     /**
  91.      *
  92.      * @param page
  93.      * 要查看第几页
  94.      * @param pageSize
  95.      * 每页记录数
  96.      */
  97.     publicvoid findByPageMySQL(int page, int pageSize) {
  98.         Connection con = null;
  99.         PreparedStatement stmt = null;
  100.         ResultSet rs = null;
  101.         int total = -1;// 总记录数
  102.         int pages = -1;// 总页数
  103.         String sql_total = "select count(*) from dept";
  104.         String sql = "select * from dept order by deptno limit ?,?";
  105.         try {
  106.             con = ConnectionSource.getConnection();
  107.             stmt = con.prepareStatement(sql_total);
  108.             // 获得总的记录数
  109.             rs = stmt.executeQuery();
  110.             if (rs.next()) {
  111.                 total = rs.getInt(1);
  112.             }
  113.             System.out.println(total);
  114.             // 计算总共需要多少页
  115.             int mod = total % pageSize;
  116.             if (mod == 0)
  117.                 pages = total / pageSize;
  118.             else
  119.                 pages = total / pageSize + 1;
  120.             // 如果要查看的页数大于最大页,或者小于1,则取最后一页或第一页
  121.             if (page > pages)
  122.                 page = pages;
  123.             elseif (page < 1) {
  124.                 page = 1;
  125.             }
  126.             int start = (page - 1) * pageSize;
  127.             stmt = con.prepareStatement(sql);
  128.             stmt.setInt(1, start);
  129.             stmt.setInt(2, pageSize);
  130.             rs = stmt.executeQuery();
  131.             while (rs.next()) {
  132.                 System.out.println(rs.getInt("deptno") + ","
  133.                         + rs.getString("dname") + "," + ","
  134.                         + rs.getString("loc"));
  135.             }
  136.         } catch (SQLException e) {
  137.             System.out.println("数据库访问异常!");
  138.             thrownew RuntimeException(e);
  139.         } finally {
  140.             try {
  141.                 if (rs != null) {
  142.                     rs.close();
  143.                 }
  144.                 if (stmt != null) {
  145.                     stmt.close();
  146.                 }
  147.                 if (con != null) {
  148.                     con.close();
  149.                 }
  150.             } catch (SQLException e) {
  151.                 System.out.println("释放资源时发生异常");
  152.             }
  153.         }
  154.     }
  155.     publicvoid findAll() {
  156.         Connection con = null;
  157.         Statement stmt = null;
  158.         ResultSet rs = null;
  159.         try {
  160.             Class.forName("oracle.jdbc.OracleDriver");
  161.             con = DriverManager.getConnection(
  162.                     "jdbc:oracle:thin:@localhost:1521:ORCL", "scott", "tiger");
  163.             stmt = con.createStatement();
  164.             rs = stmt.executeQuery("select deptno,dname,loc from dept");
  165.             while (rs.next()) {
  166.                 System.out.println(rs.getInt("deptno") + ","
  167.                         + rs.getString("dname") + "," + rs.getString("loc"));
  168.             }
  169.         } catch (ClassNotFoundException e) {
  170.             System.out.println("驱动类无法找到!");
  171.             thrownew RuntimeException(e);
  172.         } catch (SQLException e) {
  173.             System.out.println("数据库访问异常!");
  174.             thrownew RuntimeException(e);
  175.         } finally {
  176.             try {
  177.                 if (rs != null) {
  178.                     rs.close();
  179.                 }
  180.                 if (stmt != null) {
  181.                     stmt.close();
  182.                 }
  183.                 if (con != null) {
  184.                     con.close();
  185.                 }
  186.             } catch (SQLException e) {
  187.                 System.out.println("关闭连接时发生异常");
  188.             }
  189.         }
  190.     }
  191.     publicvoid add(Dept dept) {
  192.         Connection con = null;
  193.         Statement stmt = null;
  194.         int flag = -1;
  195.         String sql = "insert into dept(deptno,dname,loc) " + "values("
  196.                 + dept.getDeptno() + ",'" + dept.getDname() + "','"
  197.                 + dept.getLoc() + "')";
  198.         System.out.println(sql);
  199.         try {
  200.             con = ConnectionSource.getConnection();
  201.             stmt = con.createStatement();
  202.             flag = stmt.executeUpdate(sql);
  203.             if (flag > 0) {
  204.                 System.out.println("新增记录成功!");
  205.             }
  206.         } catch (SQLException e) {
  207.             System.out.println("数据库访问异常!");
  208.             thrownew RuntimeException(e);
  209.         } finally {
  210.             try {
  211.                 if (stmt != null) {
  212.                     stmt.close();
  213.                 }
  214.                 if (con != null) {
  215.                     con.close();
  216.                 }
  217.             } catch (SQLException e) {
  218.                 System.out.println("释放资源发生异常");
  219.             }
  220.         }
  221.     }
  222.     publicvoid update(Dept dept) {
  223.         Connection con = null;
  224.         Statement stmt = null;
  225.         int flag = -1;
  226.         String sql = "update dept set dname = '" + dept.getDname() + "',"
  227.                 + "loc = '" + dept.getLoc() + "' where deptno = "
  228.                 + dept.getDeptno();
  229.         try {
  230.             con = ConnectionSource.getConnection();
  231.             stmt = con.createStatement();
  232.             flag = stmt.executeUpdate(sql);
  233.             if (flag > 0) {
  234.                 System.out.println("更新记录成功!");
  235.             }
  236.         } catch (SQLException e) {
  237.             System.out.println("数据库访问异常!");
  238.             thrownew RuntimeException(e);
  239.         } finally {
  240.             try {
  241.                 if (stmt != null) {
  242.                     stmt.close();
  243.                 }
  244.                 if (con != null) {
  245.                     con.close();
  246.                 }
  247.             } catch (SQLException e) {
  248.                 System.out.println("释放资源发生异常");
  249.             }
  250.         }
  251.     }
  252. }

db.properties文件的完整内容如下所示:

 
  1. #jdbc.driverClassName=oracle.jdbc.OracleDriver
  2. #jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
  3. #jdbc.username=scott
  4. #jdbc.password=tiger
  5. jdbc.driverClassName=com.mysql.jdbc.Driver
  6. jdbc.url=jdbc:mysql://localhost:3306/tts7
  7. jdbc.username=root
  8. jdbc.password=root
  9. #<!-- 初始化连接 -->
  10. dataSource.initialSize=10
  11. #<!-- 最大空闲连接 -->
  12. dataSource.maxIdle=20
  13. #<!-- 最小空闲连接 -->
  14. dataSource.minIdle=5
  15. #最大连接数量
  16. dataSource.maxActive=50
  17. #<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
  18. dataSource.maxWait=1000

ConnectionSource类与之前案例一样没有变化,该类完整内容如下所示:

 
  1. import java.io.IOException;
  2. import java.sql.Connection;
  3. import java.sql.SQLException;
  4. import java.util.Properties;
  5. import org.apache.commons.dbcp.BasicDataSource;
  6. public class ConnectionSource {
  7.     private static BasicDataSource dataSource = null;
  8.     public ConnectionSource() {
  9.     }
  10.     public static void init() {
  11.         Properties dbProps = new Properties();
  12.         // 取配置文件可以根据实际的不同修改
  13.         try {
  14.             dbProps.load(ConnectionSource.class.getClassLoader().getResourceAsStream(
  15.                     "day01/v4/db.properties"));
  16.         } catch (IOException e) {
  17.             e.printStackTrace();
  18.         }
  19.         try {
  20.             String driveClassName = dbProps.getProperty("jdbc.driverClassName");
  21.             String url = dbProps.getProperty("jdbc.url");
  22.             String username = dbProps.getProperty("jdbc.username");
  23.             String password = dbProps.getProperty("jdbc.password");
  24.             String initialSize = dbProps.getProperty("dataSource.initialSize");
  25.             String minIdle = dbProps.getProperty("dataSource.minIdle");
  26.             String maxIdle = dbProps.getProperty("dataSource.maxIdle");
  27.             String maxWait = dbProps.getProperty("dataSource.maxWait");
  28.             String maxActive = dbProps.getProperty("dataSource.maxActive");
  29.             dataSource = new BasicDataSource();
  30.             dataSource.setDriverClassName(driveClassName);
  31.             dataSource.setUrl(url);
  32.             dataSource.setUsername(username);
  33.             dataSource.setPassword(password);
  34.             // 初始化连接数
  35.             if (initialSize != null)
  36.                 dataSource.setInitialSize(Integer.parseInt(initialSize));
  37.             // 最小空闲连接
  38.             if (minIdle != null)
  39.                 dataSource.setMinIdle(Integer.parseInt(minIdle));
  40.             // 最大空闲连接
  41.             if (maxIdle != null)
  42.                 dataSource.setMaxIdle(Integer.parseInt(maxIdle));
  43.             // 超时回收时间(以毫秒为单位)
  44.             if (maxWait != null)
  45.                 dataSource.setMaxWait(Long.parseLong(maxWait));
  46.             // 最大连接数
  47.             if (maxActive != null) {
  48.                 if (!maxActive.trim().equals("0"))
  49.                     dataSource.setMaxActive(Integer.parseInt(maxActive));
  50.             }
  51.         } catch (Exception e) {
  52.             e.printStackTrace();
  53.             System.out.println("创建连接池失败!请检查设置!!!");
  54.         }
  55.     }
  56.     public static synchronized Connection getConnection() throws SQLException {
  57.         if (dataSource == null) {
  58.             init();
  59.         }
  60.         Connection conn = null;
  61.         if (dataSource != null) {
  62.             conn = dataSource.getConnection();
  63.         }
  64.         return conn;
  65.     }
  66. }

5 完成NetCTOSS项目中,权限管理模块的角色的DAO设计及实现

详细要求如下:

1. 查询所有角色信息。

2. 添加某个角色。

3. 修改某个角色的角色名称。

参考答案

在课上案例的基础上,完成当前案例。工程结构如图-2所示。

图-2

本案例,在课上案例实现的基础上添加了如下内容:

1. RoleInfo.java为数据库中的role_info表和Java对象的映射;

2. RoleInfoDAO.java 为一个接口,该接口中定义了三个方法,该三个方法的声明如下所示:

 
  1. package com.tarena.netctoss;
  2. import java.sql.SQLException;
  3. import java.util.List;
  4. import com.tarena.netctoss.entity.RoleInfo;
  5. publicinterface RoleInfoDAO {
  6.     /**
  7.      * 查询所有的角色
  8.      * @return所有角色返回List集合
  9.      */
  10.     List<RoleInfo> findAll() throws SQLException;
  11.     /**
  12.      * 新增角色
  13.      * @paramrole要添加角色
  14.      * @return添加后角色,包含角色ID
  15.      */
  16.     RoleInfo save(RoleInfo role) throws SQLException;
  17.     /**
  18.      * 修改某个角色
  19.      * @paramrole要修改的角色
  20.      * @return返回修改后的角色
  21.      */
  22.     RoleInfo modify(RoleInfo role) throws SQLException;
  23. }

以上三个方法的作用,请参考注释部分。

3. RoleInfoDAOImpl.java 该类继承自BaseDAO,来直接获取创建连接的方法;另外,该类实现了RoleInfoDAO接口,将该接口中的方法做出实现。

4.TestRoleInfoDAO.java 该类用于测试RoleInfoDAOImpl所实现的方法的正确性。

实现此案例需要按照如下步骤进行。

步骤一:创建序列、表以及向表中插入数据

首先,创建名为role_seq的序列;然后,创建名为role_info的表并向该表中插入测试数据,SQL语句如下所示:

 
  1. create sequence role_seq;
  2. create table role_info(
  3.         role_id        number(4)         constraint role_info_id_pk primary key,
  4.         name         varchar2(50)     not null
  5. );
  6. insert into role_info(role_id,name)values(role_seq.nextval,'管理员');
  7. insert into role_info(role_id,name)values(role_seq.nextval,'柜台人员');
  8. insert into role_info(role_id,name)values(role_seq.nextval,'中层领导');
  9. commit;

步骤二:创建数据库中的role_info表和Java对象的映射类RoleInfo

代码如下所示:

 
  1. package com.tarena.netctoss.entity;
  2. public class RoleInfo {
  3.     private int roleId;
  4.     private String name;
  5.     public int getRoleId() {
  6.         return roleId;
  7.     }
  8.     public void setRoleId(int roleId) {
  9.         this.roleId = roleId;
  10.     }
  11.     public String getName() {
  12.         return name;
  13.     }
  14.     public void setName(String name) {
  15.         this.name = name;
  16.     }
  17.     @Override
  18.     public String toString() {
  19.         return "RoleInfo [name=" + name + ", roleId=" + roleId + "]";
  20.     }
  21. }

步骤三:创建RoleInfoDAO接口,该接口中定义了对数据的增改查的功能

代码如下所示:

 
  1. package com.tarena.netctoss;
  2. import java.sql.SQLException;
  3. import java.util.List;
  4. import com.tarena.netctoss.entity.RoleInfo;
  5. publicinterface RoleInfoDAO {
  6.     /**
  7.      * 查询所有的角色
  8.      * @return所有角色返回List集合
  9.      */
  10.     List<RoleInfo> findAll() throws SQLException;
  11.     /**
  12.      * 新增角色
  13.      * @paramrole要添加角色
  14.      * @return添加后角色,包含角色ID
  15.      */
  16.     RoleInfo save(RoleInfo role) throws SQLException;
  17.     /**
  18.      * 修改某个角色
  19.      * @paramrole要修改的角色
  20.      * @return返回修改后的角色
  21.      */
  22.     RoleInfo modify(RoleInfo role) throws SQLException;
  23. }

步骤四:创建RoleInfoDAOImpl类

创建RoleInfoDAOImpl类,该类继承自BaseDAO,来直接获取创建连接的方法;另外,该类实现了RoleInfoDAO接口,将该接口中的方法做出实现,代码如下所示:

 
  1. package com.tarena.netctoss.impl;
  2. import java.sql.Connection;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. import com.tarena.netctoss.BaseDAO;
  9. import com.tarena.netctoss.RoleInfoDAO;
  10. import com.tarena.netctoss.entity.RoleInfo;
  11. publicclass RoleInfoDAOImpl extends BaseDAO implements RoleInfoDAO {
  12.     privatestaticfinal String FIND_ALL = "SELECT role_id,name FROM ROLE_INFO";
  13.     privatestaticfinal String MODIFY = "UPDATE ROLE_INFO SET name = ? WHERE role_id=?";
  14.     privatestaticfinal String INSERT = "INSERT INTO ROLE_INFO(role_id, name) "
  15.             + " VALUES (ROLE_SEQ.NEXTVAL,?)";
  16.     @Override
  17.     public List<RoleInfo> findAll() throws SQLException {
  18.         Connection conn = getConnection();
  19.         String sql = FIND_ALL;
  20.         PreparedStatement ps = conn.prepareStatement(sql);
  21.         ResultSet rs = ps.executeQuery();
  22.         RoleInfo role = null;
  23.         List<RoleInfo> list = new ArrayList<RoleInfo>();
  24.         while (rs.next()) {
  25.             role = new RoleInfo();
  26.             role.setRoleId(rs.getInt("role_id"));
  27.             role.setName(rs.getString("name"));
  28.             list.add(role);
  29.         }
  30.         return list;
  31.     }
  32.     @Override
  33.     public RoleInfo save(RoleInfo role) throws SQLException {
  34.         Connection conn = getConnection();
  35.         String sql = INSERT;
  36.         PreparedStatement ps = conn.prepareStatement(sql,
  37.                 new String[] { "role_id" });
  38.         ps.setString(1, role.getName());
  39.         ps.executeUpdate();
  40.         ResultSet rs = ps.getGeneratedKeys();
  41.         rs.next();
  42.         int id = rs.getInt(1);
  43.         role.setRoleId(id);
  44.         return role;
  45.     }
  46.     @Override
  47.     public RoleInfo modify(RoleInfo role) throws SQLException {
  48.         Connection conn = getConnection();
  49.         String sql = MODIFY; // 预先定义好的SQL语句
  50.         PreparedStatement ps = conn.prepareStatement(sql);
  51.         ps.setString(1, role.getName());
  52.         ps.setInt(2, role.getRoleId());
  53.         int flag = ps.executeUpdate();
  54.         return (flag > 0) ? role : null;
  55.     }
  56. }

步骤五:创建TestRoleInfoDAO类,用于测试功能是否实现

创建TestRoleInfoDAO类,该类用于测试RoleInfoDAOImpl所实现的方法的正确性,代码如下所示:

 
  1. package com.tarena.netctoss;
  2. import java.sql.SQLException;
  3. import java.util.List;
  4. import com.tarena.netctoss.entity.RoleInfo;
  5. import com.tarena.netctoss.impl.RoleInfoDAOImpl;
  6. public class TestRoleInfoDAO {
  7.     public static void main(String[] args) {
  8.         TestRoleInfoDAO test=new TestRoleInfoDAO();
  9.         //test.testFindAll();
  10.         //test.testSave();
  11.         test.testModify();
  12.     }
  13.     public void testModify() {
  14.      RoleInfo role=new RoleInfo();
  15.      role.setRoleId(10);
  16.      role.setName("common");
  17.         RoleInfoDAO dao = new RoleInfoDAOImpl();
  18.         try {
  19.             role=dao.modify(role);
  20.             System.out.println(role.toString());
  21.         } catch (SQLException e) {
  22.             e.printStackTrace();
  23.         }
  24.     }
  25.     public void testSave() {
  26.      RoleInfo role=new RoleInfo();
  27.      role.setName("admin");
  28.         RoleInfoDAO dao = new RoleInfoDAOImpl();
  29.         try {
  30.             role=dao.save(role);
  31.             System.out.println(role.toString());
  32.         } catch (SQLException e) {
  33.             e.printStackTrace();
  34.         }
  35.     }
  36.     public void testFindAll() {
  37.         RoleInfoDAO dao = new RoleInfoDAOImpl();
  38.         try {
  39.             List<RoleInfo> list = dao.findAll();
  40.             for(RoleInfo role : list){
  41.                 System.out.println(role.toString());
  42.                 System.out.println("---------------------------------");
  43.             }
  44.         } catch (SQLException e) {
  45.             e.printStackTrace();
  46.         }
  47.     }
  48. }
原文地址:https://www.cnblogs.com/xyk1987/p/8331029.html