java(十三) —— JDBC(三) DAO接口 DAO接口实现类 DAO接口实现类测试

1.DAO接口

import java.sql.Connection;
import java.sql.Date;
import java.util.List;

/**
 * @author ym
 * @create 2022-02-01 14:38
 * @description 针对于Customer表的dao操作
 */
public interface CustomerDAO {
    void insert(Connection connection, Customer customer);

    void deleteById(Connection connection, int id);

    void update(Connection connection, Customer customer);

    Customer selectById(Connection connection, int id);

    List<Customer> getAll(Connection connection);

    long getCount(Connection connection);

    Date getMaxBirth(Connection connection);
}

2.DAO接口实现类

import java.sql.Connection;
import java.sql.Date;
import java.util.List;

/**
 * @author ym
 * @create 2022-02-01 14:46
 * @description
 */
public class CustomerDAOImpl extends BaseDAO implements CustomerDAO {
    @Override
    public void insert(Connection connection, Customer customer) {
        String insertSql = "insert into customers(name,email,birth) values(?,?,?)";
        update(connection, insertSql, customer.getName(), customer.getEmail(), customer.getBirth());
    }


    @Override
    public void deleteById(Connection connection, int id) {
        String insertSql = "delete from customers where id = ?";
        update(connection, insertSql, id);
    }

    @Override
    public void update(Connection connection, Customer customer) {
        String updateSql = "update customers set name=? ,email=? ,birth=? where id=?";
        update(connection, updateSql, customer.getName(), customer.getEmail(), customer.getBirth(), customer.getId());

    }

    @Override
    public Customer selectById(Connection connection, int id) {
        String selectByIdSql = "select * from customers where id =?";
        Customer customer1 = selectAllTable(connection, Customer.class, selectByIdSql, id);
        return customer1;
    }

    @Override
    public List<Customer> getAll(Connection connection) {
        String getAllSql = "select id,name,email,birth from customers";
        List<Customer> customers = selectAllTableList(connection, Customer.class, getAllSql);
        return customers;
    }

    @Override
    public long getCount(Connection connection) {
        String getCountSql = "select COUNT(*) from customers";
        Long value = getValue(connection, Long.class, getCountSql);
        return value;
    }

    @Override
    public Date getMaxBirth(Connection connection) {
        String getMaxValue = "select max(birth) from customers";
        Date value = getValue(connection, Date.class, getMaxValue);
        return value;
    }
}

3.DAO接口实现类测试


import org.junit.Test;

import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author ym
 * @create 2022-02-01 15:08
 * @description
 */
public class TestImpl {

    CustomerDAOImpl customerDAO = new CustomerDAOImpl();

    @Test
    public void testInsert() {
        //1.建立连接
        Connection connection = null;
        try {
            connection = DBUtil.getConnection();
            //2.要添加的customer
            Customer customer = new Customer();
            customer.setName("陈胜");
            customer.setEmail("chensheng@163.com");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date parse = simpleDateFormat.parse("1887-02-01");
            customer.setBirth(new Date(parse.getTime()));
            customerDAO.insert(connection, customer);
            System.out.println("添加成功");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeResource(connection, null);
        }
    }

    @Test
    public void testDelete() {
        //1.建立连接
        Connection connection = null;
        try {
            connection = DBUtil.getConnection();
            //2.要删除的customerId

            customerDAO.deleteById(connection, 4);
            System.out.println("删除成功");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeResource(connection, null);
        }
    }

    @Test
    public void testUpdate() {
        //1.建立连接
        Connection connection = null;
        try {
            connection = DBUtil.getConnection();
            //2.要修改的customer
            Customer customer = new Customer();
            customer.setName("吴广");
            customer.setEmail("wuguang@163.com");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date parse = simpleDateFormat.parse("1889-01-02");
            customer.setBirth(new Date(parse.getTime()));
            customer.setId(19);
            customerDAO.update(connection, customer);
            System.out.println("修改成功");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeResource(connection, null);
        }
    }


    @Test
    public void testSelectOne() {
        //1.建立连接
        Connection connection = null;
        try {
            connection = DBUtil.getConnection();
            //2.要查找的customerId

            Customer customer = customerDAO.selectById(connection, 20);
            System.out.println(customer.toString());
            System.out.println("查找成功");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeResource(connection, null);
        }
    }

    @Test
    public void testSelectAll() {
        //1.建立连接
        Connection connection = null;
        try {
            connection = DBUtil.getConnection();


            List<Customer> customer = customerDAO.getAll(connection);
            customer.forEach(System.out::println);
            System.out.println("查找成功");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeResource(connection, null);
        }
    }

    @Test
    public void testSelectCount() {
        //1.建立连接
        Connection connection = null;
        try {
            connection = DBUtil.getConnection();


            long customer = customerDAO.getCount(connection);
            System.out.println(customer);
            System.out.println("查找成功");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeResource(connection, null);
        }
    }

    @Test
    public void testSelectMaxBirth() {
        //1.建立连接
        Connection connection = null;
        try {
            connection = DBUtil.getConnection();


            Date customer = customerDAO.getMaxBirth(connection);
            System.out.println(customer);
            System.out.println("查找成功");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeResource(connection, null);
        }
    }
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用JDBC调用数据接口的图书管理系统DAO层的示例代码: ``` import java.sql.*; import java.util.ArrayList; import java.util.List; public class BookDao { // 数据库连接信息 private final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; private final String DB_URL = "jdbc:mysql://localhost:3306/bookdb"; private final String USER = "root"; private final String PASS = "123456"; // 查询所有图书信息 public List<Book> getAllBooks() { Connection conn = null; Statement stmt = null; ResultSet rs = null; List<Book> bookList = new ArrayList<>(); try { // 注册 JDBC 驱动器 Class.forName(JDBC_DRIVER); // 打开连接 conn = DriverManager.getConnection(DB_URL, USER, PASS); // 执行查询 stmt = conn.createStatement(); String sql = "SELECT * FROM book"; rs = stmt.executeQuery(sql); // 处理结果集 while (rs.next()) { Book book = new Book(); book.setId(rs.getInt("id")); book.setName(rs.getString("name")); book.setAuthor(rs.getString("author")); book.setPublisher(rs.getString("publisher")); book.setPrice(rs.getDouble("price")); book.setNumber(rs.getInt("number")); bookList.add(book); } } catch (SQLException se) { se.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { // 关闭资源 try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } return bookList; } // 添加图书信息 public boolean addBook(Book book) { Connection conn = null; PreparedStatement pstmt = null; boolean result = false; try { // 注册 JDBC 驱动器 Class.forName(JDBC_DRIVER); // 打开连接 conn = DriverManager.getConnection(DB_URL, USER, PASS); // 执行插入 String sql = "INSERT INTO book(name, author, publisher, price, number) VALUES (?, ?, ?, ?, ?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, book.getName()); pstmt.setString(2, book.getAuthor()); pstmt.setString(3, book.getPublisher()); pstmt.setDouble(4, book.getPrice()); pstmt.setInt(5, book.getNumber()); int count = pstmt.executeUpdate(); // 处理结果 if (count > 0) { result = true; } } catch (SQLException se) { se.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { // 关闭资源 try { if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } return result; } // 更新图书信息 public boolean updateBook(Book book) { Connection conn = null; PreparedStatement pstmt = null; boolean result = false; try { // 注册 JDBC 驱动器 Class.forName(JDBC_DRIVER); // 打开连接 conn = DriverManager.getConnection(DB_URL, USER, PASS); // 执行更新 String sql = "UPDATE book SET name=?, author=?, publisher=?, price=?, number=? WHERE id=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, book.getName()); pstmt.setString(2, book.getAuthor()); pstmt.setString(3, book.getPublisher()); pstmt.setDouble(4, book.getPrice()); pstmt.setInt(5, book.getNumber()); pstmt.setInt(6, book.getId()); int count = pstmt.executeUpdate(); // 处理结果 if (count > 0) { result = true; } } catch (SQLException se) { se.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { // 关闭资源 try { if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } return result; } // 删除图书信息 public boolean deleteBook(int id) { Connection conn = null; PreparedStatement pstmt = null; boolean result = false; try { // 注册 JDBC 驱动器 Class.forName(JDBC_DRIVER); // 打开连接 conn = DriverManager.getConnection(DB_URL, USER, PASS); // 执行删除 String sql = "DELETE FROM book WHERE id=?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, id); int count = pstmt.executeUpdate(); // 处理结果 if (count > 0) { result = true; } } catch (SQLException se) { se.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { // 关闭资源 try { if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } return result; } } ``` 这里仅提供了一个简单的示例,实际开发中还需要根据具体情况进行修改和完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值