黑马学习连接池 druid JdbcTemplate c3p0 池技术

  1 package cn.itcast.jdbctemplate;
  2 
  3 
  4 import org.junit.Test;
  5 import org.springframework.jdbc.core.BeanPropertyRowMapper;
  6 import org.springframework.jdbc.core.JdbcTemplate;
  7 
  8 import java.math.BigDecimal;
  9 import java.util.Date;
 10 import java.util.List;
 11 import java.util.Map;
 12 
 13 /*
 14  * 1. 要求 JdbcTemplate
 15  * 2. jdbcUtils工具类直接拿来用(druid.properties)
 16  * 3. 插入员工数据(完整的)
 17  * 4. 删除员工数据(按照员工编号删除)
 18  * 5. 修改员工数据(修改李逵的工资、奖金、部门)
 19  * 6. 查询所有工资大于20000万的员工, 按工资降序排列
 20  * 7. 查询所有在 2007-5-1 之后入职的员工
 21  * 8. 按部门分组,统计每组的人数
 22  *
 23  * 分析:
 24  *  1.使用jdbctemplate+druid来进行测试,准备一个DataSource对象,来创建JdbcTemplate对象
 25  *
 26  * */
 27 public class JdbcTemplate_Test {
 28     private JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidJdbcUtils.getDataSource());
 29     /**
 30      * 插入员工数据(完整的)
 31      */
 32     @Test
 33     public void test1(){
 34         Employee emp = new Employee();
 35         emp.setId(1015);
 36         emp.setEname("小白龙");
 37         emp.setJobId(4);
 38         emp.setMgr(1004);
 39         emp.setJoindate(new Date());
 40         emp.setSalary(new BigDecimal(3000));
 41         emp.setBonus(new BigDecimal(8000));
 42         emp.setDeptId(20);
 43 
 44         String sql = "insert into emp(id, ename, job_id, mgr, joindate, salary, bonus, dept_id) values(?,?,?,?,?,?,?,?)";
 45 
 46         int rows = jdbcTemplate.update(sql, emp.getId(), emp.getEname(), emp.getJobId(), emp.getMgr(),
 47                 emp.getJoindate(), emp.getSalary(), emp.getBonus(), emp.getDeptId());
 48         System.out.println(rows);
 49     }
 50 
 51     /**
 52      * 删除员工数据(按照员工编号删除)
 53      */
 54     @Test
 55     public void test2(){
 56         String sql = "delete from emp where id = ?";
 57         int rows = jdbcTemplate.update(sql, 1015);
 58         System.out.println(rows);
 59     }
 60 
 61     /**
 62      * 修改员工数据(修改李逵的工资、奖金、部门)
 63      */
 64     @Test
 65     public void test3(){
 66         String sql = "update emp set salary = ?, bonus = ?, dept_id = ? where ename = ? ";
 67         int rows = jdbcTemplate.update(sql, 2000, 2000, 20, "李逵");
 68         System.out.println(rows);
 69     }
 70 
 71     /**
 72      * 查询所有工资大于20000万的员工, 按工资降序排列
 73      */
 74     @Test
 75     public void test4(){
 76 //        TimeZone.setDefault(TimeZone.getTimeZone("GMT+10:00"));数据库是Date类型的,这里修改默认时区根本不影响结果。
 77         String sql = "select id, ename, job_id as jobId, mgr, joindate, salary, bonus, dept_id as deptId from emp where salary > ? ";
 78         List<Employee> employeeList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Employee.class), 20000);
 79         employeeList.forEach(System.out::println);
 80     }
 81 
 82     /**
 83      * 按部门分组,统计每组的人数
 84      */
 85     @Test
 86     public void test5(){
 87         String sql = "select\n" +
 88                 "\tcount(t1.id) as employee_num, t2.id as id, t2.dname as dname\n" +
 89                 "FROM\n" +
 90                 "emp as t1\n" +
 91                 "right join \n" +
 92                 "dept as t2\n" +
 93                 "on \n" +
 94                 "t1.dept_id = t2.id\n" +
 95                 "GROUP BY\n" +
 96                 "t2.id";
 97         List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
 98         mapList.forEach(System.out::println);
 99     }
100 }
JdbcTemplate操作员工表
 1 package cn.itcast.jdbctemplate;
 2 
 3 import com.alibaba.druid.pool.DruidDataSourceFactory;
 4 
 5 import javax.sql.DataSource;
 6 import java.io.IOException;
 7 import java.sql.Connection;
 8 import java.sql.ResultSet;
 9 import java.sql.SQLException;
10 import java.sql.Statement;
11 import java.util.Properties;
12 
13 public class DruidJdbcUtils {
14     //DataSource对象
15     private static DataSource dataSource;
16 
17     static {
18         try {
19             //加载配置
20             Properties props = new Properties();
21             props.load(DruidJdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
22 
23             //创建德鲁伊连接池
24             dataSource = new DruidDataSourceFactory().createDataSource(props);
25         } catch (IOException e) {
26             e.printStackTrace();
27         } catch (Exception e) {
28             e.printStackTrace();
29         }
30     }
31 
32     //获取连接池
33     public static DataSource getDataSource(){
34         return dataSource;
35     }
36 
37     //获取连接
38     public static Connection getConnection() throws SQLException {
39         return dataSource.getConnection();
40     }
41 
42     //DML语句释放资源
43     public static void release(Statement stmt, Connection conn){
44       /*  if(stmt != null){
45             try {
46                 stmt.close();
47             } catch (SQLException e) {
48                 e.printStackTrace();
49             }
50         }
51         if(conn != null){
52             try {
53                 conn.close();
54             } catch (SQLException e) {
55                 e.printStackTrace();
56             }
57         }*/
58       release(null, stmt, conn);
59     }
60 
61     //查询语句释放资源
62     public static void release(ResultSet rs, Statement stmt, Connection conn){
63         if(rs != null){
64             try {
65                 rs.close();
66             } catch (SQLException e) {
67                 e.printStackTrace();
68             }
69         }
70         if(stmt != null){
71             try {
72                 stmt.close();
73             } catch (SQLException e) {
74                 e.printStackTrace();
75             }
76         }
77         if(conn != null){
78             try {
79                 conn.close();
80             } catch (SQLException e) {
81                 e.printStackTrace();
82             }
83         }
84     }
85 }
DruidJbctUtils数据库连接工具类
  1 package cn.itcast.jdbctemplate;
  2 
  3 import java.math.BigDecimal;
  4 import java.util.Date;
  5 
  6 /*
  7 CREATE TABLE emp (
  8   id INT PRIMARY KEY, -- 员工id
  9   ename VARCHAR(50), -- 员工姓名
 10   job_id INT, -- 职务id
 11   mgr INT , -- 上级领导
 12   joindate DATE, -- 入职日期
 13   salary DECIMAL(7,2), -- 工资
 14   bonus DECIMAL(7,2), -- 奖金
 15   dept_id INT, -- 所在部门编号
 16 );
 17  */
 18 public class Employee {
 19     private Integer id;
 20     private String ename;
 21     private Integer jobId;
 22     private Integer mgr;
 23     private Date joindate;
 24     private BigDecimal salary;
 25     private BigDecimal bonus;
 26     private Integer deptId;
 27 
 28     public Employee() {
 29     }
 30 
 31     public Integer getId() {
 32         return id;
 33     }
 34 
 35     public void setId(Integer id) {
 36         this.id = id;
 37     }
 38 
 39     public String getEname() {
 40         return ename;
 41     }
 42 
 43     public void setEname(String ename) {
 44         this.ename = ename;
 45     }
 46 
 47     public Integer getJobId() {
 48         return jobId;
 49     }
 50 
 51     public void setJobId(Integer jobId) {
 52         this.jobId = jobId;
 53     }
 54 
 55     public Integer getMgr() {
 56         return mgr;
 57     }
 58 
 59     public void setMgr(Integer mgr) {
 60         this.mgr = mgr;
 61     }
 62 
 63     public Date getJoindate() {
 64         return joindate;
 65     }
 66 
 67     public void setJoindate(Date joindate) {
 68         this.joindate = joindate;
 69     }
 70 
 71     public BigDecimal getSalary() {
 72         return salary;
 73     }
 74 
 75     public void setSalary(BigDecimal salary) {
 76         this.salary = salary;
 77     }
 78 
 79     public BigDecimal getBonus() {
 80         return bonus;
 81     }
 82 
 83     public void setBonus(BigDecimal bonus) {
 84         this.bonus = bonus;
 85     }
 86 
 87     public Integer getDeptId() {
 88         return deptId;
 89     }
 90 
 91     public void setDeptId(Integer deptId) {
 92         this.deptId = deptId;
 93     }
 94 
 95     @Override
 96     public String toString() {
 97         return "Employee{" +
 98                 "id=" + id +
 99                 ", ename='" + ename + '\'' +
100                 ", jobId=" + jobId +
101                 ", mgr=" + mgr +
102                 ", joindate=" + joindate +
103                 ", salary=" + salary +
104                 ", bonus=" + bonus +
105                 ", deptId=" + deptId +
106                 '}';
107     }
108 }
Employee实体
 1 package utils;
 2 
 3 import java.io.FileReader;
 4 import java.io.IOException;
 5 import java.net.URL;
 6 import java.sql.*;
 7 import java.util.Properties;
 8 
 9 public class JDBCUtils {
10     //连接参数
11     private static String driver;
12     private static String url;
13     private static String user;
14     private static String password;
15 
16     static{
17         try {
18             //读取配置
19             Properties props = new Properties();
20             //方式一
21 //            props.load(JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
22             //方式二
23             ClassLoader cl = JDBCUtils.class.getClassLoader();
24             URL resource = cl.getResource("jdbc.properties");
25             //D:/Code/IdeaProject/IdeaCode/javaweb-T1/out/production/jdbc-day01/jdbc.properties
26             System.out.println(resource.getPath());
27             props.load(new FileReader(resource.getPath()));
28 
29             //赋值
30             driver = props.getProperty("driver");
31             url = props.getProperty("url");
32             user = props.getProperty("user");
33             password = props.getProperty("password");
34 
35             //加载驱动
36             Class.forName(driver);
37         } catch (IOException e) {
38             e.printStackTrace();
39         } catch (ClassNotFoundException e) {
40             e.printStackTrace();
41         }
42     }
43 
44     //获取连接
45     public static Connection getConnection() throws SQLException {
46         return DriverManager.getConnection(url, user, password);
47     }
48 
49 
50     //释放资源
51     public static void release(Statement stmt, Connection conn){
52         release(null, stmt, conn);
53     }
54 
55     public static void release(ResultSet rs, Statement stmt, Connection conn){
56         if(rs != null){
57             try {
58                 rs.close();
59             } catch (SQLException e) {
60                 e.printStackTrace();
61             }
62         }
63         if(stmt != null){
64             try {
65                 stmt.close();
66             } catch (SQLException e) {
67                 e.printStackTrace();
68             }
69         }
70         if(conn != null){
71             try {
72                 conn.close();
73             } catch (SQLException e) {
74                 e.printStackTrace();
75             }
76         }
77     }
78 }
JdbcUtils简单版工具类
 1 package conn;
 2 
 3 import utils.JDBCUtils;
 4 
 5 import java.sql.Connection;
 6 import java.sql.PreparedStatement;
 7 import java.sql.SQLException;
 8 
 9 public class ConnAndSql {
10     public static void main(String[] args) throws SQLException {
11         long start = System.currentTimeMillis();
12         Connection conn = JDBCUtils.getConnection();
13         long end = System.currentTimeMillis();
14 
15         System.out.println("获取连接:" + (end - start));
16 
17         start = System.currentTimeMillis();
18         String sql = "select * from account";
19         PreparedStatement pstmt = conn.prepareStatement(sql);
20         pstmt.executeQuery();
21         end = System.currentTimeMillis();
22 
23         System.out.println("执行sql:" + (end - start));
24 
25         /*
26         获取连接:543
27         执行sql:18
28          */
29     }
30 }
获取连接的时间花费远远超出了执行sql的时间,,需要使用池技术,管理连接。
  1 package pro01.service;
  2 
  3 import pro01.dao.EmployeeDao;
  4 import pro01.domain.Employee;
  5 
  6 import java.math.BigDecimal;
  7 import java.sql.SQLException;
  8 import java.util.List;
  9 import java.util.Scanner;
 10 
 11 public class EmployeeMain {
 12     private static EmployeeDao employeeDao = new EmployeeDao();
 13 
 14     private static final String prompt = "user>";
 15 
 16     public static void main(String[] args) {
 17         //显式主界面,并给出提示
 18         showMain();
 19 
 20         Scanner sc = new Scanner(System.in);
 21         while(true){
 22 
 23             System.out.print(prompt);
 24 
 25             String line = sc.nextLine();
 26             switch (line.trim().toLowerCase()){
 27                 case "1" :
 28                     findAllProc();break;
 29                 case "2" :
 30                     deleteProc();break;
 31                 case "3" :
 32                     insertProc();break;
 33                 case "4" :
 34                     updateProc();break;
 35                 case "5" :
 36                     showMain();break;
 37                 case "exit" :
 38                     return;
 39                 default:
 40                     System.out.println("输入有误,请重新输入!");
 41             }
 42         }
 43     }
 44 
 45     private static void showMain() {
 46         System.out.println("1 查询所有员工信息");
 47         System.out.println("2 删除员工");
 48         System.out.println("3 新增员工");
 49         System.out.println("4 修改员工信息");
 50         System.out.println("5 显示主界面");
 51         System.out.println("exit 退出程序");
 52     }
 53 
 54     private static void updateProc() {
 55         //请输入要修改的员工编号
 56         Scanner sc = new Scanner(System.in);
 57         System.out.println("请输入要修改的员工编号");
 58         System.out.print(prompt);
 59 
 60         //获取id
 61         String idStr = sc.nextLine();
 62         Integer id = null;
 63         try{
 64             id = Integer.parseInt(idStr);
 65         } catch (NumberFormatException e){
 66             System.out.println("输入有误");
 67             return;
 68         }
 69 
 70         //根据id,查找用户,判断是否存在
 71         Employee employee = employeeDao.findById(id);
 72         if(employee == null){
 73             System.out.println("员工不存在");
 74             return;
 75         }
 76 
 77         //封装修改条件
 78         employee = new Employee();
 79         employee.setId(id);
 80 
 81         //姓名
 82         System.out.println("请输入员工姓名");
 83         System.out.print(prompt);
 84         String name = sc.nextLine();
 85         if(!"".equals(name.trim())){
 86             employee.setName(name);
 87         }
 88 
 89         //薪水
 90         System.out.println("请输入员工薪水");
 91         System.out.print(prompt);
 92         String salaryStr = sc.nextLine();
 93         if(!"".equals(salaryStr.trim())){
 94             try{
 95                 BigDecimal salary = new BigDecimal(salaryStr);
 96                 employee.setSalary(salary);
 97             }catch (NumberFormatException e){
 98                 System.out.println("输入的薪水应该是数字");
 99                 return;
100             }
101         }
102 
103         boolean isSuccess = false;
104         try {
105             isSuccess = employeeDao.updateById(employee);
106         } catch (SQLException e) {
107             System.out.println("数据库错误");
108             return;
109         }
110         if(isSuccess){
111             System.out.println("更新成功");
112         }else{
113             System.out.println("更新失败");
114         }
115     }
116 
117     private static void insertProc() {
118         Scanner sc = new Scanner(System.in);
119         //员工编号
120         System.out.println("请输入员工编号:");
121         System.out.print(prompt);
122         String idStr = sc.nextLine();
123         int id;
124         try{
125             id = Integer.parseInt(idStr);
126         } catch (NumberFormatException e) {
127             System.out.println("员工编号输入错误,只能是正数");
128             return;
129         }
130         //员工姓名
131         System.out.println("请输入员工姓名:");
132         System.out.print(prompt);
133         String name = sc.nextLine();
134         //员工薪资
135         System.out.println("请输入员工薪资:");
136         System.out.print(prompt);
137         String salaryStr = sc.nextLine();
138         BigDecimal salary = null;
139         try{
140             salary = new BigDecimal(salaryStr);
141         }catch (NumberFormatException e){
142             System.out.println("工资必须为有效的数字");
143             return;
144         }
145 
146         Employee employee = new Employee();
147         employee.setId(id);
148         employee.setName(name);
149         employee.setSalary(salary);
150 
151         boolean isSuccess = false;
152         try {
153             isSuccess = employeeDao.add(employee);
154         } catch (SQLException e) {
155             System.out.println("数据库错误");
156             return;
157         }
158         if(isSuccess){
159             System.out.println("添加成功");
160         }else{
161             System.out.println("添加失败");
162         }
163     }
164 
165     private static void deleteProc() {
166         //请输入要删除的员工编号
167         Scanner sc = new Scanner(System.in);
168         System.out.println("请输入要删除的员工编号");
169         System.out.print(prompt);
170 
171         //获取id
172         String idStr = sc.nextLine();
173         int id;
174         try{
175             id = Integer.parseInt(idStr);
176         } catch (NumberFormatException e){
177             System.out.println("输入有误");
178             return;
179         }
180 
181         //根据id,查找用户,判断是否存在
182         Employee employee = employeeDao.findById(id);
183         if(employee == null){
184             System.out.println("员工不存在");
185             return;
186         }
187 
188         //如果用户存在,则删除用户
189         boolean isSuccess = employeeDao.deleteById(id);
190         if(isSuccess){
191             System.out.println("删除成功");
192         }else{
193             System.out.println("删除失败");
194         }
195     }
196 
197     private static void findAllProc() {
198        List<Employee> list =  employeeDao.findAll();
199 
200         System.out.println("员工编号\t员工姓名\t员工薪资");
201         list.forEach(e->{
202             System.out.println(e.getId() + "\t\t" + e.getName() + "\t\t" + e.getSalary());
203         });
204     }
205 }
cmdCRUD 主界面
 1 package pro01.domain;
 2 
 3 import java.math.BigDecimal;
 4 
 5 /*
 6 create table employee(
 7 id int primary key auto_increment,
 8 name varchar(50),
 9 salary DECIMAL
10 );
11  */
12 public class Employee {
13     private Integer id;
14     private String name;
15     private BigDecimal salary;
16 
17     public Employee() {
18     }
19 
20     public Integer getId() {
21         return id;
22     }
23 
24     public void setId(Integer id) {
25         this.id = id;
26     }
27 
28     public String getName() {
29         return name;
30     }
31 
32     public void setName(String name) {
33         this.name = name;
34     }
35 
36     public BigDecimal getSalary() {
37         return salary;
38     }
39 
40     public void setSalary(BigDecimal salary) {
41         this.salary = salary;
42     }
43 }
cmdCRUD 员工类
  1 package pro01.dao;
  2 
  3 import pro01.domain.Employee;
  4 
  5 import java.sql.*;
  6 import java.util.ArrayList;
  7 import java.util.List;
  8 
  9 public class EmployeeDao {
 10     /**
 11      * 查询全部员工信息
 12      * @return
 13      */
 14     public List<Employee> findAll() {
 15         String driver = "com.mysql.jdbc.Driver";
 16         String url = "jdbc:mysql://localhost:3307/jdbc_db";
 17         String user = "root";
 18         String password = "root";
 19 
 20         Connection conn = null;
 21         PreparedStatement pstmt = null;
 22         ResultSet rs = null;
 23 
 24         List<Employee> employeeList = new ArrayList<>();
 25         try {
 26             //连接
 27            conn = DriverManager.getConnection(url, user, password);
 28             //语句
 29             String sql = "select * from employee";
 30             pstmt = conn.prepareStatement(sql);
 31             //执行
 32             rs = pstmt.executeQuery();
 33             while(rs.next()){
 34                 //读取记录数据,封装为Employee对象
 35                 Employee emp = new Employee();
 36                 emp.setId(rs.getInt("eid"));
 37                 emp.setName(rs.getString("ename"));
 38                 emp.setSalary(rs.getBigDecimal("salary"));
 39 
 40                 //将员工添加到集合
 41                 employeeList.add(emp);
 42             }
 43         } catch (SQLException e) {
 44             e.printStackTrace();
 45         } finally{
 46             if(rs != null) {
 47                 try {
 48                     rs.close();
 49                 } catch (SQLException e) {
 50                     e.printStackTrace();
 51                 }
 52             }
 53             if(pstmt != null) {
 54                 try {
 55                     pstmt.close();
 56                 } catch (SQLException e) {
 57                     e.printStackTrace();
 58                 }
 59             }
 60             if(conn != null) {
 61                 try {
 62                     conn.close();
 63                 } catch (SQLException e) {
 64                     e.printStackTrace();
 65                 }
 66             }
 67         }
 68         return employeeList;
 69     }
 70 
 71     public Employee findById(int id) {
 72         String driver = "com.mysql.jdbc.Driver";
 73         String url = "jdbc:mysql://localhost:3307/jdbc_db";
 74         String user = "root";
 75         String password = "root";
 76 
 77         Connection conn = null;
 78         PreparedStatement pstmt = null;
 79         ResultSet rs = null;
 80 
 81         Employee employee = null;
 82         try {
 83             //连接
 84             conn = DriverManager.getConnection(url, user, password);
 85             //语句
 86             String sql = "select * from employee where eid = ? ";
 87             pstmt = conn.prepareStatement(sql);
 88             pstmt.setInt(1, id);
 89             //执行
 90             rs = pstmt.executeQuery();
 91             if(rs.next()){
 92                 //读取记录数据,封装为Employee对象
 93                 employee = new Employee();
 94                 employee.setId(rs.getInt("eid"));
 95                 employee.setName(rs.getString("ename"));
 96                 employee.setSalary(rs.getBigDecimal("salary"));
 97             }
 98         } catch (SQLException e) {
 99             e.printStackTrace();
100         } finally{
101             if(rs != null) {
102                 try {
103                     rs.close();
104                 } catch (SQLException e) {
105                     e.printStackTrace();
106                 }
107             }
108             if(pstmt != null) {
109                 try {
110                     pstmt.close();
111                 } catch (SQLException e) {
112                     e.printStackTrace();
113                 }
114             }
115             if(conn != null) {
116                 try {
117                     conn.close();
118                 } catch (SQLException e) {
119                     e.printStackTrace();
120                 }
121             }
122         }
123         return employee;
124     }
125 
126     public boolean deleteById(int id) {
127         String driver = "com.mysql.jdbc.Driver";
128         String url = "jdbc:mysql://localhost:3307/jdbc_db";
129         String user = "root";
130         String password = "root";
131 
132         Connection conn = null;
133         PreparedStatement pstmt = null;
134         try{
135             //获取连接对象
136             conn = DriverManager.getConnection(url, user, password);
137             //获取语句
138             String sql = "delete from employee where eid = ? ";
139             pstmt = conn.prepareStatement(sql);
140             pstmt.setInt(1, id);
141             //执行
142             int count = pstmt.executeUpdate();
143             //如果条数大于0,表示删除成功
144             return count > 0 ? true : false;
145         } catch (SQLException e) {
146             e.printStackTrace();
147         } finally{
148             if(pstmt != null) {
149                 try {
150                     pstmt.close();
151                 } catch (SQLException e) {
152                     e.printStackTrace();
153                 }
154             }
155             if(conn != null) {
156                 try {
157                     conn.close();
158                 } catch (SQLException e) {
159                     e.printStackTrace();
160                 }
161             }
162         }
163         return false;
164     }
165 
166 
167     public boolean add(Employee employee) throws SQLException {
168         String driver = "com.mysql.jdbc.Driver";
169         String url = "jdbc:mysql://localhost:3307/jdbc_db";
170         String user = "root";
171         String password = "root";
172 
173         Connection conn = null;
174         PreparedStatement pstmt = null;
175         try{
176             //获取连接对象
177             conn = DriverManager.getConnection(url, user, password);
178             //获取语句
179             String sql = "insert into employee(eid, ename, salary) values(?,?,?)";
180             pstmt = conn.prepareStatement(sql);
181             pstmt.setInt(1, employee.getId());
182             pstmt.setString(2,employee.getName());
183             pstmt.setBigDecimal(3, employee.getSalary());
184             //执行
185             int count = pstmt.executeUpdate();
186             //如果条数大于0,表示删除成功
187             return count > 0 ? true : false;
188         }  finally{
189             if(pstmt != null) {
190                 try {
191                     pstmt.close();
192                 } catch (SQLException e) {
193                     e.printStackTrace();
194                 }
195             }
196             if(conn != null) {
197                 try {
198                     conn.close();
199                 } catch (SQLException e) {
200                     e.printStackTrace();
201                 }
202             }
203         }
204     }
205 
206     public boolean updateById(Employee employee) throws SQLException {
207         String driver = "com.mysql.jdbc.Driver";
208         String url = "jdbc:mysql://localhost:3307/jdbc_db";
209         String user = "root";
210         String password = "root";
211 
212         Connection conn = null;
213         PreparedStatement pstmt = null;
214         try{
215             //获取连接对象
216             conn = DriverManager.getConnection(url, user, password);
217             //获取语句
218             ArrayList<Object> args = new ArrayList<>();
219             StringBuilder sb = new StringBuilder();
220 
221             if(employee.getName() != null){
222                 sb.append(",ename=? ");
223                 args.add(employee.getName());
224             }
225             if(employee.getSalary() != null){
226                 sb.append(",salary=? ");
227                 args.add(employee.getSalary());
228             }
229 
230             int argsNum = args.size();
231             if(argsNum == 0){
232                 return false;
233             }
234             String sql = "update employee set " + sb.deleteCharAt(0).toString() + "where eid=? ";
235 
236             pstmt = conn.prepareStatement(sql);
237 
238             for (int i = 0; i < argsNum; i++) {
239                 pstmt.setObject(i + 1, args.get(i));
240             }
241             pstmt.setObject(argsNum + 1, employee.getId());
242             //执行
243             int count = pstmt.executeUpdate();
244             //如果条数大于0,表示删除成功
245             return count > 0 ? true : false;
246         } finally{
247             if(pstmt != null) {
248                 try {
249                     pstmt.close();
250                 } catch (SQLException e) {
251                     e.printStackTrace();
252                 }
253             }
254             if(conn != null) {
255                 try {
256                     conn.close();
257                 } catch (SQLException e) {
258                     e.printStackTrace();
259                 }
260             }
261         }
262     }
263 }
cmdCRUD 数据库操作类employeeDao

猜你喜欢

转载自www.cnblogs.com/mozq/p/10747627.html