提交自由编程作业,请老师检查

来源:3-6 自由编程

Mycheol

2020-08-26 09:34:09

package com.imooc.jdbc.hrapp.command;

import java.sql.*;
import java.util.Scanner;

public class PriceQueryCommand1 implements Command {
    @Override
    public void excute() {
        System.out.println("查询价格在1500以上,3500以下的商品价格:");
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            //1、加载并注册JDBC驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2、创建数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/imooc?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true", "root", "cmz95217s");
            //3、创建statement对象
            String sql = "SELECT * FROM goods WHERE price>? AND price<?";
            pstmt = connection.prepareStatement(sql);
            pstmt.setFloat(1, 1500);
            pstmt.setFloat(2, 3500);
            rs = pstmt.executeQuery();
            //4、遍历查询结果
            while (rs.next()) {
                Integer id = rs.getInt(1);
                String name = rs.getString("name");
                Float price = rs.getFloat("price");
                String desp = rs.getString("desp");
                System.out.println(id + " " + name + " " + price + " " + desp);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //5、关闭连接,释放资源
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Command cmd = new PriceQueryCommand1();
        cmd.excute();
    }
}


写回答

1回答

好帮手慕小班

2020-08-26

同学的代码完成的不错,继续加油。祝:学习愉快~

0

0 学习 · 16556 问题

查看课程