自由编程作业打卡,请老师检查!
来源:3-2 自由编程
Mycheol
2020-08-25 16:02:25
CREATE TABLE goods ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(20) NOT NULL, price FLOAT NOT NULL, desp VARCHAR(30) NOT NULL ); INSERT INTO goods (name,price,desp) VALUES ("手机",2000,"黑色,存储容量32G"), ("冰箱",1500,"银色,对开门"), ("洗衣机",3000,"滚筒"), ("空调",4000,"变频空调");
package com.imooc.jdbc.hrapp.command; import java.sql.*; import java.util.Scanner; //这里的Command接口就是老师上节课视频那个接口,就没贴出来了,直接贴实现类的代码 public class PriceQueryCommand implements Command { @Override public void excute() { System.out.println("请输入一个价格以获取低于此售价的商品信息:"); Scanner in = new Scanner(System.in); float qprice = in.nextFloat(); Connection connection = null; Statement stmt = 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对象 stmt = connection.createStatement(); rs = stmt.executeQuery("SELECT * FROM goods WHERE price<" + qprice); //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 PriceQueryCommand(); cmd.excute(); } }
1回答
同学你好,课题完成的不错,很棒,继续加油
祝学习愉快
相似问题