目录
1.要求
2.代码结构及环境配置
3.功能介绍
4. 代码
1.要求
- 使用Java + JDBC +MySQL 完成
- 所有数据存入数据库
2.代码结构及环境配置
技术点
数据库
数据存储
MySQL
连接池
Druid
代码分层
在开发中,在监听用户页面操作的同时可能需要操作数据库,例如登陆,需要监听用户输入,又要查询数据库,如果将代码都写到一个类中,这样会导致代码很混乱,因为类中有“界面”的代码又有“操作数据库”的代码,可否优化呢?--可以,将代码进行分层
视图层
负责界面交互和处理交互逻辑,和用户打交道
数据层
专门处理数据库,和数据库打交道
名称约束
XXXView:某个视图层类
XXXDao(Data Access Object):数据层
环境配置
spring jdbc jar包
poi jar包
mysql驱动
导入数据库(准备数据):
配置文件:druid.properties:
工具类(代码):
md5:
package utils; import java.security.MessageDigest; public class Md5 { public static String md5(String key) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; try { byte[] btInput = key.getBytes(); // 获得MD5摘要算法的 MessageDigest 对象 MessageDigest mdInst = MessageDigest.getInstance("MD5"); // 使用指定的字节更新摘要 mdInst.update(btInput); // 获得密文 byte[] md = mdInst.digest(); // 把密文转换成十六进制的字符串形式 int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { return null; } } }Constant:public class Constant { public static int getImportSize(int size) { if (size >= 10000000) { return 100000; } if (size >= 1000000) { return 10000; } if (size >= 100000) { return 10000; } if (size >= 10000) { return 1000; } if (size >= 1000) { return 100; } if (size >= 100) { return 10; } return 1; } }JDBCUtils:
public class JDBCUtils { // 加载配置文件 static DataSource ds; static { Properties pro = new Properties(); try { pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties")); ds = DruidDataSourceFactory.createDataSource(pro); } catch (Exception e) { e.printStackTrace(); } } public static DataSource getDataSource() { return ds; } public static Connection getConnection() throws SQLException { return ds.getConnection(); } public static void close(ResultSet rs, Statement st, Connection conn) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (st != null) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }3.功能介绍
打开:D:学习javajava学习书籍管理系统2022_05_22_20_44_29.xlsx
将template.xlsx导入数据库中:
打开:D:学习javajava学习书籍管理系统2022_05_22_20_48_20.xlsx
4. 代码
代码文件:Java书籍管理系统(jdbcmysqlpoi)-Java文档类资源-CSDN文库
具体代码:
public class FailureBook { private String name; private String author; private String price; //异常信息 private String errorMsg; public String getErrorMsg() { return errorMsg; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } public FailureBook(String name, String author, String price, String errorMsg) { this.name = name; this.author = author; this.price = price; this.errorMsg = errorMsg; } public FailureBook() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } @Override public String toString() { return "[name='" + name + ''' + ", author='" + author + ''' + ", price='" + price + ''' + "], errorMsg='" + errorMsg; } }public class Book { private Integer id; private String name; private String author; private int price; public Book() { } public Book(String name, String author, int price) { this.name = name; this.author = author; this.price = price; } public Book(Integer id, String name, String author, int price) { this.id = id; this.name = name; this.author = author; this.price = price; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "Book{" + "id=" + id + ", name='" + name + ''' + ", author='" + author + ''' + ", price=" + price + '}'; } }public class Admin { private Integer id; private String name; private String password; public Admin() { } public Admin(String name, String password) { this.name = name; this.password = password; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "Admin{" + "id=" + id + ", name='" + name + ''' + ", password='" + password + ''' + '}'; } }import view.AdminView; import view.BookView; public class Main { public static void main(String[] args) { while (true) { new AdminView().run(); new BookView().run(); } } }import dao.AdminDao; import domain.Admin; import utils.Md5; import java.util.List; import java.util.Scanner; public class AdminView { Scanner sc = new Scanner(System.in); AdminDao dao = new AdminDao(); public void run() { while (true) { System.out.println("----------数据管理系统----------"); System.out.println("1.登陆 2.查看管理员 3.添加管理员 4.退出系统"); System.out.println("请输入操功能的序号[1-4]:"); int i = sc.nextInt(); switch (i) { case 3: addAdmin(); break; case 4: System.out.println("退出成功!"); System.exit(-1); default: if (dao.getCount() > 0) { switch (i) { case 1: if (login()) { System.out.println("登陆成功!"); return; } System.out.println("你的用户名或密码错误!"); break; case 2: printAdmin(); break; default: System.out.println("无该功能,请重新选择!"); break; } } else { System.out.println("没有管理员信息"); } } } } private void printAdmin() { List admins = dao.findAll(); System.out.println("idttnamettpassword"); for (Admin admin : admins) { System.out.println(admin.getId() + "tt" + admin.getName() + "tt*****"); } } private void addAdmin() { System.out.println("请输入用户名:"); String name = sc.next(); //判断name是否存在 if (dao.findAdminByName(name)) { System.out.println("请输入密码:"); String password = sc.next(); Admin admin = new Admin(name, Md5.md5(name + password)); if (dao.addAdmin(admin)) { System.out.println("添加成功"); } else { System.out.println("添加失败"); } } else { System.out.println("该用户名已存在"); } } private boolean login() { System.out.println("请输入用户名:"); String name = sc.next(); System.out.println("请输入密码:"); String password = sc.next(); Admin admin = new Admin(name, Md5.md5(name + password)); //根据用户名查询数据库 if (dao.findAdmin(admin) != null) { return true; } else { return false; } } }import domain.Admin; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import utils.JDBCUtils; import java.util.List; public class AdminDao { JdbcTemplate jt = new JdbcTemplate(JDBCUtils.getDataSource()); public Admin findAdmin(Admin admin) { String sql = "SELECT * FROM admin WHERe name = ? AND password = ?"; Object[] objs = {admin.getName(), admin.getPassword()}; try { return jt.queryForObject(sql, objs, new BeanPropertyRowMapper<>(Admin.class)); } catch (DataAccessException e) { //若用户输入的用户名或密码错误 //解决方法一:抛异常 return null; } // 解决方式二: // List admins = jt.query(sql, objs, new BeanPropertyRowMapper<>(Admin.class)); // return admins.isEmpty() ? null : admins.get(0); } public Long getCount() { String sql = "select count(*) from admin"; return jt.queryForObject(sql, Long.class); } public boolean findAdminByName(String name) { String sql = "select * from admin where name = ?"; Object[] params = {name}; List admins = jt.query(sql, params, new BeanPropertyRowMapper(Admin.class)); return admins.isEmpty(); } public boolean addAdmin(Admin admin) { String sql = "insert into admin(name,password) values(?,?)"; Object[] params = {admin.getName(), admin.getPassword()}; return jt.update(sql, params) > 0; } public List findAll() { String sql = "select * from admin"; return jt.query(sql, new BeanPropertyRowMapper<>(Admin.class)); } }import com.monitorjbl.xlsx.StreamingReader; import dao.BookDao; import domain.Book; import domain.FailureBook; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.*; import utils.Constant; import java.io.*; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Scanner; import java.util.stream.Stream; public class BookView { Scanner sc = new Scanner(System.in); BookDao dao = new BookDao(); public void run() { while (true) { System.out.println("----------书籍管理----------"); System.out.println("1.添加书籍 2.编辑书籍 3.删除书籍 4.查询书籍 5.退出系统 6.退出登入 7.导出Excel表格 8.从Excel表格中导入"); int i = sc.nextInt(); switch (i) { case 1: addBook(); break; case 5: System.out.println("退出成功!"); System.exit(-1); break; case 6: System.out.println("退出登陆成功!"); return; case 8: try { importExcel(); } catch (FileNotFoundException e) { e.printStackTrace(); } break; default: if (dao.getCount() > 0) { switch (i) { case 2: editBook(); break; case 3: deleteBook(); break; case 4: selectBook(); break; case 7: exportExcel(); break; default: System.out.println("无该功能,请重新选择!"); break; } } else { System.out.println("没有书籍数据。"); } break; } } } private void importExcel() throws FileNotFoundException { String path; while (true) { System.out.println("请输入正确的文件名:"); path = sc.next(); if (!new File(path).isFile()) { System.out.println("路径不正确,必须是文件"); } else { break; } } //读取Excel表格 File file = new File(path); FileInputStream fis = new FileInputStream(file); Workbook wk = StreamingReader.builder() //缓冲到内存中的行数 .rowCacheSize(10000) //内存大小 .bufferSize(4096 * 2).open(fis); // 获取工作表 Sheet sheet = wk.getSheetAt(0); //合法表头 String[] titles = {"name", "author", "price"}; //记录行数 int readCount = 0; int lastRowNum = sheet.getLastRowNum(); //存储多行(所有)数据 List> list = new ArrayList<>(); //存储所有异常 List
failureBooks = new ArrayList<>(); //遍历行 for (Row row : sheet) { readCount++; if (readCount == 2) { for (Cell cell : row) { String value = cell.getStringCellValue(); if (!titles[cell.getColumnIndex()].equals(value)) { System.out.println("表格格式不正确"); return; } } } if (readCount > 2) { //存储一行数据 List rowList = new ArrayList<>(); //遍历列 for (Cell cell : row) { rowList.add(cell.getStringCellValue()); } String name = rowList.get(0); String author = rowList.get(1); String price = rowList.get(2); try { if ("".equals(name) && "".equals(author) && "".equals(price)) { //可能读到了空行 continue; } if ("".equals(name) || "".equals(author) || "".equals(price)) { //name、author、price可能为空 throw new RuntimeException("name、author、price不能为空"); } try { //判断price是否合法 if (Integer.parseInt(price) < 0) { throw new RuntimeException("price必须大于等于0"); } } catch (NumberFormatException e) { throw new RuntimeException("price必须是整数类型"); } list.add(rowList); } catch (RuntimeException e) { //如果出现一次异常,那么表示当前行数据是错误的 //将当前行的异常进行封装 FailureBook f = new FailureBook(name, author, price, e.getMessage()); failureBooks.add(f); } } } //遍历数据 for (List strings : list) { System.out.println(strings); } //遍历异常数据 for (FailureBook f : failureBooks) { System.out.println(f); } //导入数据 //使用批处理 //什么时候导入数据? //如果list大小等于可导入的大小 //获取读取到最后一个数据,那么就进行导入 if ((!list.isEmpty() && (list.size() >= Constant.getImportSize(lastRowNum)) || (readCount == lastRowNum))) { List import domain.Book; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import utils.JDBCUtils; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; public class BookDao { JdbcTemplate jt = new JdbcTemplate(JDBCUtils.getDataSource()); public boolean addBook(Book book) { String sql = "insert into book(name,author,price) values(?,?,?)"; return jt.update(sql, book.getName(), book.getAuthor(), book.getPrice()) > 0; } public Long getCount() { String sql = "select count(*) from book"; return jt.queryForObject(sql, Long.class); } public ListgetAllBook() { String sql = "select * from book"; return jt.query(sql, new BeanPropertyRowMapper<>(Book.class)); } public boolean deleteBook(int id) { String sql = "delete from book where id = ?"; return jt.update(sql, id) > 0; } public boolean editBook(Book books) { String sql = "update book set name = ? ,author = ? , price = ? where id = ?"; Object[] params = {books.getName(), books.getAuthor(), books.getPrice(), books.getId()}; return jt.update(sql, params) > 0; } public List selectBookByPrice(int min, int max) { String sql = "select * from book where price between ? and ?"; Object[] params = {min, max}; return jt.query(sql, params, new BeanPropertyRowMapper<>(Book.class)); } public int[] batchAdd(List



