jdbc编程练习题---以后可以套用

题目描述

有一个图书管理系统,包含学生和图书信息,且图书可以进行分类,学生可以在一个时间范围内借阅图书,并在这个时间范围内归还图书。表和表关系如下:

DROP DATABASE IF EXISTS ebook;

CREATE DATABASE ebook CHARACTER SET 'utf8mb4';

USE ebook;

– Table structure for category

DROP TABLE IF EXISTS category;

CREATE TABLE category (

 id int(11) PRIMARY KEY AUTO_INCREMENT,

 name varchar(20)

);

– Records of category

INSERT INTO category VALUES (1, '历史');

INSERT INTO category VALUES (2, '艺术');

INSERT INTO category VALUES (3, '计算机');

INSERT INTO category VALUES (4, '数学');

INSERT INTO category VALUES (5, '小说');

– Table structure for student

DROP TABLE IF EXISTS student;

CREATE TABLE student (

 id int(11) PRIMARY KEY AUTO_INCREMENT,

 name varchar(20)

);


– Records of student

INSERT INTO student VALUES (1, '王昭君');

INSERT INTO student VALUES (2, '李白');

INSERT INTO student VALUES (3, '貂蝉');

INSERT INTO student VALUES (4, '小乔');

INSERT INTO student VALUES (5, '韩信');


– Table structure for book

DROP TABLE IF EXISTS book;

CREATE TABLE book (

 id int(11) PRIMARY KEY AUTO_INCREMENT,

 name varchar(20),

 author varchar(20),

 price decimal(10, 2),

 category_id int(11),

 CONSTRAINT fk_book_category_id FOREIGN KEY (category_id) REFERENCES category (id)

);

– Records of book

INSERT INTO book VALUES (1, '深入理解Java虚拟机', '周志明', 57.90, 3);

INSERT INTO book VALUES (2, '西游记', '吴承恩', 30.68, 5);

INSERT INTO book VALUES (3, '儒林外史', '吴敬梓', 18.80, 5);

INSERT INTO book VALUES (4, '聊斋志异', '蒲松龄', 21.00, 5);

INSERT INTO book VALUES (5, '史记', '司马迁', 278.20, 1);

INSERT INTO book VALUES (6, '资治通鉴', '司马光', 524.00, 1);

INSERT INTO book VALUES (7, 'Java核心技术 卷I:基础知识', 'Cay S. Horstmann', 92.50, 3);

INSERT INTO book VALUES (8, 'Java核心技术卷II:高级特性', 'Cay S. Horstmann', 111.20, 3);

INSERT INTO book VALUES (9, 'Java多线程编程核心技术', '高洪岩', 47.50, 3);

INSERT INTO book VALUES (10, '诗经', '孔子', 22.00, 2);

INSERT INTO book VALUES (11, '唐诗三百首', '蘅塘居士', 49.30, 2);

INSERT INTO book VALUES (12, '唐诗三百首', '蘅塘居士', 55.00, 2);

INSERT INTO book VALUES (13, '西游记', '吴承恩', 47.50, 5);

INSERT INTO book VALUES (14, '唐诗三百首', '蘅塘居士', 56.50, 2);


– Table structure for borrow_info

DROP TABLE IF EXISTS borrow_info;

CREATE TABLE borrow_info (

 id int(11) PRIMARY KEY AUTO_INCREMENT,

 book_id int(11),

 student_id int(11),

 start_time timestamp null,

 end_time timestamp null,

 CONSTRAINT fk_borrow_info_book_id FOREIGN KEY (book_id) REFERENCES book (id),

 CONSTRAINT fk_borrow_info_student_id FOREIGN KEY (student_id) REFERENCES student (id)

);

– Records of borrow_info

INSERT INTO borrow_info VALUES (1, 1, 1, '2018-11-07 18:50:43', '2018-12-07 18:51:01');

INSERT INTO borrow_info VALUES (2, 7, 1, '2019-07-10 10:21:00', '2019-09-10 10:21:00');

INSERT INTO borrow_info VALUES (3, 8, 1, '2019-09-10 10:21:00', '2019-10-10 10:21:00');

INSERT INTO borrow_info VALUES (4, 2, 2, '2019-03-02 16:37:00', '2019-04-02 16:37:00');

INSERT INTO borrow_info VALUES (5, 4, 2, '2019-03-12 14:25:00', '2019-04-12 14:25:00');

INSERT INTO borrow_info VALUES (6, 10, 2, '2019-07-13 16:21:00', '2019-10-13 16:21:00');

INSERT INTO borrow_info VALUES (7, 11, 2, '2019-06-09 09:40:00', '2019-07-09 09:40:00');

INSERT INTO borrow_info VALUES (8, 13, 2, '2019-01-03 15:11:00', '2019-04-03 15:11:00');

INSERT INTO borrow_info VALUES (9, 7, 3, '2019-05-15 13:13:00', '2019-06-15 13:13:00');

INSERT INTO borrow_info VALUES (10, 8, 3, '2019-04-27 13:53:00', '2019-05-27 13:53:00');

INSERT INTO borrow_info VALUES (11, 9, 3, '2019-06-01 11:32:00', '2019-07-01 11:32:00');

INSERT INTO borrow_info VALUES (12, 3, 4, '2019-07-01 09:40:00', '2019-08-01 09:40:00');

INSERT INTO borrow_info VALUES (13, 4, 4, '2019-06-19 11:40:00', '2019-07-19 11:40:00');

INSERT INTO borrow_info VALUES (14, 5, 4, '2019-06-25 09:23:00', '2019-09-25 09:23:00');

INSERT INTO borrow_info VALUES (15, 10, 4, '2019-08-27 15:30:00', '2019-09-27 15:30:00');

INSERT INTO borrow_info VALUES (16, 5, 5, '2019-01-23 14:20:00', '2019-04-23 14:20:00');

INSERT INTO borrow_info VALUES (17, 6, 5, '2019-03-09 10:45:00', '2019-04-09 10:45:00');

INSERT INTO borrow_info VALUES (18, 10, 5, '2019-06-17 11:32:00', '2019-09-17 11:32:00');

要求:

  1. 新增貂蝉同学的借阅记录:诗经,从2019年9月25日17:50到2019年10月25日17:50

  2. 查询计算机分类下的图书借阅信息

  3. 修改图书《深入理解Java虚拟机》的价格为61.20

  4. 删除id最大的一条借阅记录


工具类Util

/**
 * Created with IntelliJ IDEA.
 * Description:工具类,把数据库连接的基本步骤封装了起来
 * User: starry
 * Date: 2021 -03 -21
 * Time: 14:00
 */
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class Util {

    //使用连接池
    private static final DataSource DATA_SOURCE = new MysqlDataSource();

    static {
        ((MysqlDataSource) DATA_SOURCE).setUrl("jdbc:mysql://localhost:3306/ebook?useSSL=false");
        ((MysqlDataSource) DATA_SOURCE).setUser("root");
        ((MysqlDataSource) DATA_SOURCE).setPassword("111111");
    }

    public static void main(String[] args) {
        System.out.println(getConnection());
    }

    // 获取数据库连接
    public static Connection getConnection(){
        try {
            return DATA_SOURCE.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("获取数据库连接失败", e);
        }
    }

    // 释放资源
    public static void close(ResultSet resultSet, Statement statement, Connection connection){
        try {
            if(resultSet != null) {
                resultSet.close();
            }
            if(statement != null){
                statement.close();
            }
            if(connection != null){
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException("数据库操作异常", e);
        }
    }

    //日期字符串转Java日期类Date和sql时间戳Timestamp
    public static Timestamp getTimestamp(String dateString){
        try {
            // 年-月-日 小时:分钟:秒
            java.util.Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateString);
            return new java.sql.Timestamp(date.getTime());
        } catch (ParseException e) {
            throw new RuntimeException("日期格式化错误:"+dateString, e);
        }
    }

}

增加操作

  1. 新增貂蝉同学的借阅记录:诗经,从2019年9月25日17:50到2019年10月25日17:50

sql语句:

方法一:
insert into borrow_info(book_id,student_id,start_time,end_time) values
(10,3,'2019-9-25 17:50','2019-10-25 17:50');

方法二:
insert into borrow_info(book_id, student_id, start_time, end_time) 
select b.id,s.id,'2019-09-25 17:50:00','2019-10-25 17:50:00' 
from book b,student s 
where b.name='诗经' and s.name='貂蝉';

jdbc编程

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:增加操作
 * User: starry
 * Date: 2021 -03 -21
 * Time: 14:08
 */
public class Add {

    /**
     * 新增貂蝉同学的借阅记录:诗经,从2019年9月25日17:50到2019年10月25日17:50
     */

    public static void main(String[] args) {
        //1.创建数据库连接对象
        Connection connection = null;
        //2.创建操作命令对象
        PreparedStatement preparedStatement = null;
        try {
            connection = Util.getConnection();
            String sql = "insert into borrow_info(book_id, student_id," +
                    " start_time, end_time) select b.id,s.id,?,?" +
                    " from book b,student s where b.name=? and s.name=?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setTimestamp(1, Util.getTimestamp("2019-09-25 17:50:00"));
            preparedStatement.setTimestamp(2, Util.getTimestamp("2019-10-25 17:50:00"));
            preparedStatement.setString(3, "诗经");
            preparedStatement.setString(4, "貂蝉");
            System.out.println(preparedStatement);
            //3.执行sql
            int result = preparedStatement.executeUpdate();
            System.out.println(result);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //4.释放资源
            Util.close(null, preparedStatement, connection);
        }
    }

}

查询操作

  1. 查询计算机分类下的图书借阅信息

sql语句:

方法一:
select  borrow_info.*
from borrow_info,book,category
where book.category_id = category.id and
book.id = borrow_info.book_id and
category.id = 3;

方法二:
SELECT bk.NAME book_name,bk.author book_author,s.NAME student_name,bi.start_time,bi.end_time 
FROM borrow_info bi 
JOIN book bk ON bi.book_id = bk.id 
JOIN category c ON bk.category_id = c.id 
JOIN student s ON bi.student_id = s.id 
WHERE c.NAME = '计算机';

jdbc编程

import java.sql.*;

/**
 * Created with IntelliJ IDEA.
 * Description:查询操作
 * User: starry
 * Date: 2021 -03 -21
 * Time: 14:15
 */
public class Select {
    /**
     * 查询计算机分类下的图书借阅信息
     * @param args
     */
    public static void main(String[] args) {
        Connection connection    = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = Util.getConnection();
            String sql = "SELECT bk.NAME book_name,bk.author book_author," +
                    "s.NAME student_name,bi.start_time,bi.end_time" +
                    " FROM borrow_info bi JOIN book bk ON bi.book_id = bk.id" +
                    " JOIN category c ON bk.category_id = c.id" +
                    " JOIN student s ON bi.student_id = s.id" +
                    " WHERE c.NAME = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, "计算机");
            System.out.println(preparedStatement);
            resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                String  bookName  = resultSet.getString("book_name");
                String  bookAuthor = resultSet.getString("book_author");
                String  studentName = resultSet.getString("student_name");
                Timestamp startTime  = resultSet.getTimestamp("start_time");
                Timestamp  endTime   = resultSet.getTimestamp("end_time");
                System.out.println(String.format("书名:%s,作者:%s,借阅者:%s," +
                                "借阅起始日期:%s,结束日期:%s",
                        bookName, bookAuthor, studentName, startTime, endTime));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Util.close(resultSet, preparedStatement, connection);
        }
    }
}

修改操作

  1. 修改图书《深入理解Java虚拟机》的价格为61.20

sql语句:

update book set price = 61.20 where name = "深入理解Java虚拟机";

jdbc编程

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:修改操作
 * User: starry
 * Date: 2021 -03 -21
 * Time: 14:18
 */
public class Update {

    /**
     * 修改图书《深入理解Java虚拟机》的价格为61.20
     */

    public static void main(String[] args) {
        Connection connection    = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = Util.getConnection();
            String sql = "update book set price=? where name =?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setBigDecimal(1, new BigDecimal("61.20"));
            preparedStatement.setString(2, "深入理解Java虚拟机");
            System.out.println(preparedStatement);
            int result = preparedStatement.executeUpdate();
            System.out.println(result);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Util.close(null, preparedStatement, connection);
        }
    }

}

删除操作

  1. 删除id最大的一条借阅记录

sql语句:

方法一:
delete from borrow_info order by id desc limit 1;

方法二:
delete from borrow_info 
where id =(select r.id from (select max(id) id from borrow_info) r);

jdbc编程


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:删除操作
 * User: starry
 * Date: 2021 -03 -21
 * Time: 14:20
 */
public class Delete {

    /**
     * 删除id最大的一条借阅记录
     */

    public static void main(String[] args) {
        Connection connection    = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = Util.getConnection();
            String sql = "delete from borrow_info where id =" +
                    "(select r.id from (select max(id) id from borrow_info) r)";
            preparedStatement = connection.prepareStatement(sql);
            System.out.println(preparedStatement);
            int result = preparedStatement.executeUpdate();
            System.out.println(result);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Util.close(null, preparedStatement, connection);
        }
    }

}

  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值