1 设计商品对象

public class Product {private Long id;private String productName;private String brand;private String supplier;private BigDecimal salePrice;private BigDecimal costPrice;private Double cutoff;private Long dir_id;//分类编号public Long getId() {return id;}public String getProductName() {return productName;}public String getBrand() {return brand;}public String getSupplier() {return supplier;}public BigDecimal getSalePrice() {return salePrice;}public BigDecimal getCostPrice() {return costPrice;}public Double getCutoff() {return cutoff;}public Long getDir_id() {return dir_id;}public void setId(Long id) {this.id = id;}public void setProductName(String productName) {this.productName = productName;}public void setBrand(String brand) {this.brand = brand;}public void setSupplier(String supplier) {this.supplier = supplier;}public void setSalePrice(BigDecimal salePrice) {this.salePrice = salePrice;}public void setCostPrice(BigDecimal costPrice) {this.costPrice = costPrice;}public void setCutoff(Double cutoff) {this.cutoff = cutoff;}public void setDir_id(Long dir_id) {this.dir_id = dir_id;}@Overridepublic String toString() {return "Product [id=" + id + ", productName=" + productName + ", brand=" + brand + ", suppliet=" + supplier+ ", salePrice=" + salePrice + ", costPrice=" + costPrice + ", cutoff=" + cutoff + ", dir_id=" + dir_id+ "]";}
}

2 设计实现DAO接口

import java.util.List;import cn.itsource._05_.shopping.domain.Product;public interface IProductDAO {void save(Product pro);void delete(Long id);void update(Product pro);//long id 包装进去productProduct get(Long id);List<Product> list();}

3 使用Statment增删改查的实现类

public class ProductDAOImpl implements IProductDAO {public void save(Product pro) {Connection conn = null;Statement st = null;try {conn = JdbcUtil.INSTANCE.getConn();st = conn.createStatement();//使用StringBuilder可以减少性能的损耗,不然每次都要创建一个对象然后更改数据!StringBuilder sql = new StringBuilder();sql.append("insert into product (productName,brand,supplier,salePrice,costPrice,cutoff,dir_id ) values (");sql.append("'").append(pro.getProductName()).append("'").append(",");sql.append("'").append(pro.getBrand()).append("'").append(",");sql.append("'").append(pro.getSupplier()).append("'").append(",");sql.append("'").append(pro.getSalePrice()).append("'").append(",");sql.append("'").append(pro.getCostPrice()).append("'").append(",");sql.append("'").append(pro.getCutoff()).append("'").append(",");sql.append("'").append(pro.getDir_id()).append("'");sql.append(")");st.executeUpdate(sql.toString());} catch (Exception e) {e.printStackTrace();} finally {JdbcUtil.INSTANCE.close(conn, st, null);}}public void delete(Long id) {Connection conn = null;Statement st = null;try {conn = JdbcUtil.INSTANCE.getConn();st = conn.createStatement();String sql = "delete from product where id = " + id;st.executeUpdate(sql);} catch (Exception e) {e.printStackTrace();} finally {JdbcUtil.INSTANCE.close(conn, st, null);}}public void update(Product pro) {Connection conn = null;Statement st = null;try {conn = JdbcUtil.INSTANCE.getConn();st = conn.createStatement();StringBuilder sql = new StringBuilder();sql.append("update product set ");sql.append("productName = ").append("'").append(pro.getProductName()).append("',");sql.append("brand =").append("'").append(pro.getBrand()).append("',");sql.append("supplier =").append("'").append(pro.getSupplier()).append("',");sql.append("salePrice =").append(pro.getSalePrice()).append(",");sql.append("costPrice =").append(pro.getCostPrice()).append(",");sql.append("cutoff =").append(pro.getCutoff()).append(",");sql.append("dir_id =").append(pro.getDir_id());sql.append(" where id = ").append(pro.getId());st.executeUpdate(sql.toString());} catch (Exception e) {e.printStackTrace();} finally {JdbcUtil.INSTANCE.close(conn, st, null);}}public Product get(Long id) {Connection conn = null;Statement st = null;ResultSet rs = null;try {conn = JdbcUtil.INSTANCE.getConn();st = conn.createStatement();String sql = "select * from product where id = " + id;rs = st.executeQuery(sql);if (rs.next()) {Product pro = new Product();//把一行数据中的,每一列的值,存储到对象的属性中pro.setId(rs.getLong("id"));pro.setProductName(rs.getString("productName"));pro.setBrand(rs.getString("brand"));pro.setSupplier(rs.getString("supplier"));pro.setSalePrice(rs.getBigDecimal("salePrice"));pro.setCostPrice(rs.getBigDecimal("costPrice"));pro.setCutoff(rs.getDouble("cutoff"));pro.setDir_id(rs.getLong("dir_id"));return pro;}} catch (Exception e) {e.printStackTrace();} finally {JdbcUtil.INSTANCE.close(conn, st, rs);}return null;}public List<Product> list() {List<Product> list = new ArrayList<Product>();Connection conn = null;Statement st = null;ResultSet rs = null;try {conn = JdbcUtil.INSTANCE.getConn();st = conn.createStatement();String sql = "select * from product";rs = st.executeQuery(sql);while (rs.next()) {//把当前的数据,封装成一个Product对象Product pro = new Product();list.add(pro);//把一行数据中的,每一列的值,存储到对象的属性中pro.setId(rs.getLong("id"));pro.setProductName(rs.getString("productName"));pro.setBrand(rs.getString("brand"));pro.setSupplier(rs.getString("supplier"));pro.setSalePrice(rs.getBigDecimal("salePrice"));pro.setCostPrice(rs.getBigDecimal("costPrice"));pro.setCutoff(rs.getDouble("cutoff"));pro.setDir_id(rs.getLong("dir_id"));}} catch (Exception e) {e.printStackTrace();} finally {JdbcUtil.INSTANCE.close(conn, st, rs);}return list;}
}

4 使用PreparedStatment增删改查的实现类

public class ProductDAOpreImpl implements IProductDAO {public void save(Product pro) {Connection conn = null;PreparedStatement ps = null;try {conn = JdbcUtil.INSTANCE.getConn();String sql = "insert into product (productName,brand,supplier,salePrice,costPrice,cutoff,dir_id ) values (?,?,?,?,?,?,?)";ps = conn.prepareStatement(sql);ps.setString(1, pro.getProductName());ps.setString(2, pro.getBrand());ps.setString(3, pro.getSupplier());ps.setBigDecimal(4, pro.getSalePrice());ps.setBigDecimal(5, pro.getCostPrice());ps.setDouble(6, pro.getCutoff());ps.setLong(7, pro.getDir_id());ps.executeUpdate();} catch (Exception e) {e.printStackTrace();} finally {JdbcUtil.INSTANCE.close(conn, ps, null);}}public void delete(Long id) {Connection conn = null;PreparedStatement ps = null;try {conn = JdbcUtil.INSTANCE.getConn();String sql = "delete from product where id = ?";ps = conn.prepareStatement(sql);ps.setLong(1, id);ps.executeUpdate();} catch (Exception e) {e.printStackTrace();} finally {JdbcUtil.INSTANCE.close(conn, ps, null);}}public void update(Product pro) {Connection conn = null;PreparedStatement ps = null;try {conn = JdbcUtil.INSTANCE.getConn();String sql = "UPDATE product SET productName = ?, brand = ?, supplier = ?, salePrice = ?, costPrice = ?, cutoff = ?, dir_id = ?  WHERE id = ?";ps = conn.prepareStatement(sql );ps.setString(1, pro.getProductName());ps.setString(2, pro.getBrand());ps.setString(3, pro.getSupplier());ps.setBigDecimal(4, pro.getSalePrice());ps.setBigDecimal(5, pro.getCostPrice());ps.setDouble(6, pro.getCutoff());ps.setLong(7, pro.getDir_id());ps.setLong(8,pro.getId());ps.executeUpdate();} catch (Exception e) {e.printStackTrace();} finally {JdbcUtil.INSTANCE.close(conn, ps, null);}}public Product get(Long id) {Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {conn = JdbcUtil.INSTANCE.getConn();String sql = "select * from product where id = ?";ps = conn.prepareStatement(sql);ps.setLong(1, id);rs = ps.executeQuery();if (rs.next()) {Product pro = new Product();pro.setId(rs.getLong("id"));pro.setProductName(rs.getString("productName"));pro.setBrand(rs.getString("brand"));pro.setSupplier(rs.getString("supplier"));pro.setSalePrice(rs.getBigDecimal("salePrice"));pro.setCostPrice(rs.getBigDecimal("costPrice"));pro.setCutoff(rs.getDouble("cutoff"));pro.setDir_id(rs.getLong("dir_id"));return pro;}} catch (Exception e) {e.printStackTrace();} finally {JdbcUtil.INSTANCE.close(conn, ps, rs);}return null;}public List<Product> list() {List<Product> list = new ArrayList<>();Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {conn = JdbcUtil.INSTANCE.getConn();String sql = "SELECT * FROM product";ps = conn.prepareStatement(sql);rs = ps.executeQuery();while (rs.next()) {Product pro = new Product();list.add(pro);pro.setId(rs.getLong("id"));pro.setProductName(rs.getString("productName"));pro.setBrand(rs.getString("brand"));pro.setSupplier(rs.getString("supplier"));pro.setSalePrice(rs.getBigDecimal("salePrice"));pro.setCostPrice(rs.getBigDecimal("costPrice"));pro.setCutoff(rs.getDouble("cutoff"));pro.setDir_id(rs.getLong("dir_id"));}} catch (Exception e) {e.printStackTrace();} finally {JdbcUtil.INSTANCE.close(conn, ps, rs);}return list;}
}

5 测试实现类

public class ProductDAOTest {private IProductDAO dao = new ProductDAOImpl();@Testpublic void testSave() {Product pro = new Product();pro.setProductName("iphone8s");pro.setBrand("apple");pro.setSupplier("苹果公司");pro.setSalePrice(new BigDecimal("7000"));pro.setCostPrice(new BigDecimal("2000"));pro.setCutoff(0.9);pro.setDir_id(3L);pro.setId(4L);dao.save(pro);}@Testpublic void testDelete() {dao.delete(6L);}@Testpublic void testUpdate() {Product pro = new Product();pro.setProductName("iphone6s");pro.setBrand("apple2");pro.setSupplier("苹果公司2");pro.setSalePrice(new BigDecimal("6000"));pro.setCostPrice(new BigDecimal("1000"));pro.setCutoff(0.8);pro.setDir_id(5L);pro.setId(5L);dao.update(pro);}@Testpublic void testGet() {Product pro = dao.get(10L);System.out.println(pro);}@Testpublic void testList() {List<Product> list = dao.list();for (Product p : list) {System.out.println(p);}}
}

6 代码重构JdbcUtil类的设计

public enum JdbcUtil {INSTANCE;private static Properties p = new Properties();//只需要注册一次驱动即可,没必要每次都注册,放到jdbcutil类的静态代码块中(当字节码被加载进jvm,就会执行)static {try {//从classpath的根路径去加载db.properties文件InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");p.load(inStream);Class.forName(p.getProperty("driverClassName"));} catch (Exception e) {e.printStackTrace();}}/*** 创建connection对象* @return*/public Connection getConn() {try {return DriverManager.getConnection(p.getProperty("url"), p.getProperty("usename"),p.getProperty("password"));} catch (Exception e) {e.printStackTrace();}return null;}public void close(Connection conn, Statement st, ResultSet rs) {try {if (rs != null) {rs.close();}} catch (Exception e) {e.printStackTrace();} finally {try {if (st != null) {st.close();}} catch (Exception e) {e.printStackTrace();} finally {try {if (conn != null) {conn.close();}} catch (Exception e) {e.printStackTrace();}}}}
}

JDBC的DML增删改查的代码重构设计(上)相关推荐

  1. JDBC的DML增删改查的代码重构设计(下)

    JDBC的操作模板: 流程:1.创建ProductResultSetHandler对象:2.作为参数传递给query方法3.在query方法中:rsh.handler,其实调用的是ProductRes ...

  2. JDBC+MySQL入门增删改查案例

    目录 前言 案例分析 核心思路拆解 案例涉及知识点 第一关 创建数据库和项目 创建数据库 创建项目 第二关 JDBC插入和查询 预备工作 单个插入 批量插入 查询数据 JDBC修改和删除 修改数据 删 ...

  3. easyui增删改查前段代码

    easyui增删改查前段代码 <script>var url;//添加用户窗体 function newUser(){$('#dlg').dialog('open').dialog('se ...

  4. 【02】Java进阶:18-MySQL基础、数据库概述、数据库的安装/卸载/启动/登录、SQL概述、DDL操作数据库、DDL操作表、DML增删改查、

    day18-MySql基础 今日内容 数据库概述 数据库安装和卸载 SQL语句 DDL-----操作数据库,操作表 DML-----操作记录(增删改) DQL------操作记录(查) 学习目标 能够 ...

  5. jsp+Servlet+JavaBean+JDBC+MySQL项目增删改查

    1简单的Mvc,分层建包. java resources src/mian/java (1)dao 包 JDBC连接类,连接数据库.增删改查方法,其他的方法. (2)model包 实体类,数据库字段, ...

  6. 增删改查java代码_程序员:听说你正在为天天写增删改查代码而烦恼

    有相当多的一部分程序员一直都只接触业余应用的功能,天天写业务代码的程序员也被戏称为CURD程序员,CURD就是增(create).改(update).查(read).删(delete)的意思. CUR ...

  7. Mybatis的基本增删改查(代码)

    3.CRUD增删改查 3.1.namespace namespace中的包名要和Mapper接口的包名一致 3.2.select 选择.查询语句: id就是对应的namespace中的方法名: res ...

  8. mysql增删改查不区分大小写吗_MySQL的增删改查语句以及数据库设计的三大范式...

    数据库设计的三大范式: 1.列的原子性,即列是不可再分的 2.表里的每一列都应该与主键有关系, 3.表里的每一列都应该与主键有直接关系, 当使用自增长列不满足2.3范式,是特殊例子,只用在解决较为复杂 ...

  9. JDBC(实现增删改查的通用操作)

    JDBC JDBC概述 创建表以及相对应的对象(ORM) 表 对象 获取连接的方式 方式一 方式二 方式三 方式四 方式五(推荐使用) 增.删.改操作 查询操作 JDBC概述 为了使Java编写的程序 ...

最新文章

  1. 特征选择过滤法之方差选择、双样本t检验、方差分析、相关系数法、卡方检验、互信息法
  2. IBM又双叒叕要分拆了,IT基础设施部门将剥离,未来专注云计算和AI
  3. 常考数据结构与算法:用两个栈实现队列
  4. 简书自动上传工具出现多余空行的问题及解决方案
  5. java人种_实在看不出藏族有大量矮黑血统
  6. 北科大计算机技术研招考纲,北京科技大学2021年全国硕士研究生招生考试自命题科目考试大纲...
  7. 《avascript 高级程序设计(第三版)》 ---第二章 在HTML中使用Javascript
  8. 大数据之-Hadoop3.x_Hadoop_HDFS_掉线时限参数设置---大数据之hadoop3.x工作笔记0079
  9. 《WCF技术内幕》翻译5:第1部分_第1章_蓝月亮:WCF介绍和本章小结
  10. 分布式一致性算法 之 Paxos算法
  11. 排除IIS特殊管理困惑
  12. 《码出高效 Java开发手册》第八章 单元测试 (未整理)
  13. Spring的核心机制依赖注入简介
  14. 爬虫学习(七)——使用代理服务器进行数据爬取
  15. 有关C#中的引用类型的内存问题
  16. struts框架——ActionForm+DynaActionForm
  17. PDF连接服务器信息,远程连接服务器.pdf
  18. word2016插入公式技巧2
  19. 做谷粒商城电脑配置不够怎么办?
  20. 15.2,opencv绘制人脸识别框

热门文章

  1. 最详细的 Spring Boot 多模块开发与排坑指南
  2. Flask模板参数传值的方法
  3. html模板文件打开空白,Webpack打包index打开空白
  4. linux mem cache,Linux内存:MemTotal、MemFree、MemAvailable三者区别
  5. java中的post的作用,JSP、Servlet中get请求和post请求的区别总结
  6. Memory存储引擎
  7. flutter版本的玩Android客户端
  8. PAT1105:Spiral Matrix
  9. C++读写注册表的问题
  10. 想要把日志在两个blog同步太过麻烦了