JDBC编程相关知识(实现图书管理系统进阶版)(上)

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: JDBC编程相关知识(实现图书管理系统进阶版)

一、配置MySQL数据库驱动包

进入maven的中央仓库https://mvnrepository.com/在搜索框中输入mysql,找到与自己电脑上MySQL版本相关的jar包进行下载,如MySQL为5.x版本,那jar包也选择5.x版本:

点击对应版本后,点击jar进行下载:

在idea中创建一个项目,并创建一个lib文件夹,将下载好的jar包放到文件夹lib下,然后双击lib选择Add as...完成配置。

二、JDBC常规操作

1、创建数据源

DataSource dataSource=new MysqlDataSource();
//设置数据库所在地址
((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/library?characterEncoding=utf8&useSSL=false");
//设置数据库用户名
((MysqlDataSource) dataSource).setUser("root");
//设置数据库的登录密码
((MysqlDataSource) dataSource).setPassword("1789");

url的格式为:jdbc:mysql://服务器地址:端口/数据库名?参数名=参数值

2、建立连接

Connection connection = (Connection) dataSource.getConnection();


3、操作数据库,执行sql语句

以删除数据为例:

String sql="delete from book where name=?";
PreparedStatement statement=connection.prepareStatement(sql);
statement.setString(1,name);
statement.executeUpdate()

在sql语句中有些数据是不确定的需要用户输入,就暂时用?替代,然后再使用statement.setxx()进行替换,最后对语句进行执行,对于插入、修改、删除操作利用 executeUpdate()执行,返回值为一个整数表示多少行受影响,而对于查询操作使用executeQuery()执行,返回的是一张表,需要使用ResultSet结果集接收,并利用其next()方法对得到的结果集进行遍历,例如:对于book表查找得到的内容进行输出:

  String sql="select * from book";
        PreparedStatement statement=connection.prepareStatement(sql);
        ResultSet resultSet = statement.executeQuery();
        while(resultSet.next()){
            int id=resultSet.getInt("id");
            String name=resultSet.getString("name");
            String author=resultSet.getString("author");
            Double price=resultSet.getDouble("price");
            String theme=resultSet.getString("theme");
            boolean isBorrowed=resultSet.getBoolean("statue");
            Date borrowTime=resultSet.getDate("borrow_time");
            Date returnTime=resultSet.getDate("return_time");
            System.out.println("Book{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", author='" + author + '\'' +
                    ", price=" + price +
                    ", theme='" + theme + '\'' +
                    ", isBorrowed=" + isBorrowed +
                    ", borrowTime=" + borrowTime +
                    ", returnTime=" + returnTime +
                    '}');
        }

4、关闭资源

对于JDBC中资源使用完毕后要进行关闭,对于先使用的资源后关闭,对于后使用的资源先关闭,以上述的查找操作为例:

 resultSet.close();
 statement.close();
 connection.close();

三、JDBC实现图书管理系统

之前在JavaSE实现了图书管理系统,但是每次运行结束后数据也随之丢失,也不符合实际应用,那么使用JDBC连接MySQL数据库就可以实现。

1、建表

针对图书管理的需求,需要建立存放书的表、管理员表和普通用户表。

create table book(id int primary key,name varchar(50) not null,
price double(3,1) not null,theme varchar(20) not null,
statue boolean default false,borrow_time datetime,return_time datetime);
create table administrator(id int primary key auto_increment,name varchar(20),password varchar(20));
create table regularuser(id int primary key auto_increment,name varchar(20),password varchar(20));

三个表的结构分别为:

 

2、连接数据库

创建DBUtil类,其中定义了一个静态方法返回数据库的连接,在之后的操作数据库时进行使用。

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.SQLException;
 
public class DBUtil {
    public static Connection getConnection() throws SQLException {
        //1.创建数据源
        DataSource dataSource =new MysqlDataSource();
        //设置数据库所在地址
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/library?characterEncoding=utf8&useSSL=false");
        //设置数据库用户名
        ((MysqlDataSource) dataSource).setUser("root");
        //设置数据库的登录密码
        ((MysqlDataSource) dataSource).setPassword("1234");
        //2.建立连接
        Connection connection = (Connection) dataSource.getConnection();
        return connection;
    }
 
}

3、创建实体类

实体可以分为两类:书和用户,书包含书类和书架类,用户包含管理员类和普通用户类

为什么还要定义类?直接操作表不就行

当时这个问题也是困惑了我很久,但是在写代码时就会发现整个项目之间没有联系,没有封装性,比如在后面登录时选择身份时如果没有类就很难完成,有了类使整个项目联系密切,逻辑性强。


a、Book类

表示书类,相对于se版本的图书系统,增加了借书时间和还书时间两个属性,并且书类和创建的book表的内容几乎一致。 定义了两个构造方法,一个包含所有的属性,另一个没有包含是否借出、借书时间和还书时间。

import java.util.Date;
import java.util.Objects;
 
public class Book {
    private int id;//图书编号
    private String name;//图书名称
    private String author;//图书作者
    private double price;//图书价格
    private String theme;//图书主题
    private boolean isBorrowed;//图书是否被借出
    private Date borrowTime;//借阅时间
    private Date returnTime;//归还时间
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
 
    public Date getBorrowTime() {
        return borrowTime;
    }
 
    public void setBorrowTime(Date borrowTime) {
        this.borrowTime = borrowTime;
    }
 
    public Date getReturnTime() {
        return returnTime;
    }
 
    public void setReturnTime(Date returnTime) {
        this.returnTime = returnTime;
    }
 
    public Book(int id,String name, String author, double price, String theme) {
        this.id=id;
        this.name = name;
        this.price=price;
        this.author = author;
        this.theme = theme;
        this.isBorrowed = false;//默认未借出
    }
 
    public Book(int id, String name, String author, double price, String theme, boolean isBorrowed, Date borrowTime, Date returnTime) {
        this.id = id;
        this.name = name;
        this.author = author;
        this.price = price;
        this.theme = theme;
        this.isBorrowed = isBorrowed;
        this.borrowTime = borrowTime;
        this.returnTime = returnTime;
    }
 
    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 getTheme() {
        return theme;
    }
 
    public void setTheme(String theme) {
        this.theme = theme;
    }
 
    public boolean isBorrowed() {
        return isBorrowed;
    }
 
    public void setBorrowed(boolean borrowed) {
        isBorrowed = borrowed;
    }
 
    public double getPrice() {
        return price;
    }
 
    public void setPrice(double price) {
        this.price = price;
    }
 
    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                ", theme='" + theme + '\'' +
                ", isBorrowed=" + isBorrowed +
                ", borrowTime=" + borrowTime +
                ", returnTime=" + returnTime +
                '}';
    }
 
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Book book = (Book) o;
        return isBorrowed == book.isBorrowed && Objects.equals(name, book.name) && Objects.equals(author, book.author) && Objects.equals(theme, book.theme);
    }

b、BookShelf类

仍然需要书架类,便于之后对book表的各种操作,但是构造方法发生了改变,之前的currentSize书架当前存放书本书目是固定的,并且默认是书架中存放了几本书,而现在需要统计Book表中存放了多少条数据,在此使用了全列查询,对得到的结果集遍历,将书存放到书架上,并且得到currentSize的大小。


import util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
 
public class Bookshelf {
    private Book[] books ;//书架类
    private int size;//书架当前存放图书的数目
    private int currentSize=0;
    public Bookshelf(int size) {
        books = new Book[size];
        this.size=size;
    }
    public Bookshelf() throws SQLException {
        books = new Book[10000];//默认能存放10000本书
        this.size=10000;
        Connection connection= DBUtil.getConnection();
        String sql="select * from book";
        PreparedStatement statement=connection.prepareStatement(sql);
        ResultSet resultSet = statement.executeQuery();
        int count=0;
        while(resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            String author = resultSet.getString("author");
            Double price = resultSet.getDouble("price");
            String theme = resultSet.getString("theme");
            boolean isBorrowed = resultSet.getBoolean("statue");
            Date borrowTime = resultSet.getTime("borrow_time");
            Date returnTime = resultSet.getTime("return_time");
            books[count++] = new Book(id, name, author, price, theme, isBorrowed, borrowTime, returnTime);
        }
        this.currentSize=count;
    }
 
 
    public int getCurrentSize()  {
        return this.currentSize;
 
    }
 
    public void setCurrentSize(int currentSize) {
        this.currentSize = currentSize;
    }
 
    public int getSize() {
        return size;
    }
 
    public void setSize(int size) {
        this.size = size;
    }
 
    /**
     * 获取指定位置的图书
     * @param pos
     * @return
     */
    public Book getBook(int pos){
        if(pos>=size){
            System.out.println("已超出书架当前容量");
        }else{
            return books[pos];
        }
        return null;
    }
    public void addBook(Book book){
        books[currentSize]=book;
    }
 
    /**
     * 修改指定位置的图书
     * @param pos
     * @param book
     * @return
     */
    public void modify(int pos,Book book){
        if(pos>=size){
            System.out.println("已超出书架当前容量");
            return ;
        }else{
            books[pos]=book;
        }
    }
}

c、User类

User类是管理员和普通用户的父类,因为在登录时登录时选择不同身份来对数据库进行操作,除了表中属性,还需要定义一个接口数组用于存放各种对书架的相关操作方法,需要一个展示菜单的方法并返回选项,然后再定义一个doWork()方法是依据选项来操作数据库。还需要定义一个身份验证的方法。

import book.Bookshelf;
import operate.Operate;
import java.sql.SQLException;
 
public abstract class User {
    public int id;//用户编号
    public String name;//用户姓名
    public String password;//用户密码
    public Operate[] operates;
    public int getId() {
        return id;
    }
 
    public void setId(int 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;
    }
 
    public User( String name, String password) {
 
        this.name = name;
        this.password = password;
    }
 
    public User() {
    }
    public abstract int menu();
    public  void doWork(int option, Bookshelf books) throws SQLException {
         this.operates[option].work(books);
    }
    public abstract boolean authentication(String name, String pwd)throws SQLException;
 
}

JDBC编程相关知识(实现图书管理系统进阶版)(下):https://developer.aliyun.com/article/1520474

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助     相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
20天前
|
SQL Java 数据库连接
从零开启 JDBC 编程
从零开启 JDBC 编程
|
21天前
|
SQL Java 数据库连接
JDBC编程相关知识(实现图书管理系统进阶版)(下)
JDBC编程相关知识(实现图书管理系统进阶版)
30 0
|
24天前
|
SQL Java 关系型数据库
JavaWeb(JDBC编程)看这一篇就够了 —— 如何使用Java操作mysql数据库
JavaWeb(JDBC编程)看这一篇就够了 —— 如何使用Java操作mysql数据库
16 0
|
25天前
|
SQL Java 关系型数据库
Java之JDBC数据库编程
Java之JDBC数据库编程
14 2
|
1月前
|
SQL Java 关系型数据库
JDBC编程
JDBC编程
18 2
|
1月前
|
Java 关系型数据库 MySQL
【JDBC编程】基于MySql的Java应用程序中访问数据库与交互数据的技术
【JDBC编程】基于MySql的Java应用程序中访问数据库与交互数据的技术
|
1月前
|
SQL Java 数据库连接
Java从入门到精通:2.3.1数据库编程——学习JDBC技术,掌握Java与数据库的交互
ava从入门到精通:2.3.1数据库编程——学习JDBC技术,掌握Java与数据库的交互
|
1月前
|
SQL Java 关系型数据库
MySQL之JDBC(二)
MySQL之JDBC(二)
39 0
|
1月前
|
关系型数据库 MySQL Java
MySQL之JDBC(一)
MySQL之JDBC
37 0
|
1月前
|
关系型数据库 MySQL Java
MySQL的主从复制 && SpringBoot整合Sharding-JDBC解决读写分离
MySQL的主从复制 && SpringBoot整合Sharding-JDBC解决读写分离
45 0