请老师检查

来源:3-6 自由编程

谁叫我这么坏

2020-11-23 14:34:42

public interface Command {
public void execute();
}
import java.sql.*;
import java.util.Scanner;

public class PrepareQueryCommand implements Command {

@Override
public void execute() {
System.out.println("请输入商品价格查询的最大值:");
Scanner sc=new Scanner(System.in);
float max=sc.nextFloat();
//1、加载并注册JDBC驱动
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
//2、创建数据库连接
String url="jdbc:mysql://localhost:3306/jdbc?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
conn=DriverManager.getConnection(url,"root","root");
//3、创建PreparedStatement对象
String sql="select * from goods where price<=?";
pstmt=conn.prepareStatement(sql);
pstmt.setFloat(1,max);
rs=pstmt.executeQuery();
//4、遍历查询结果
int count=1;
System.out.printf("%-4s%-6s%-5s%-7s%-10s","序号","商品id","商品名称","商品价格","商品描述");
System.out.println();
while(rs.next()){
int id=rs.getInt(1);
String name= rs.getString(2);
float price=rs.getFloat(3);
String desp=rs.getString(4);
System.out.printf("%-5s%-7s%-7s%-10s%-10s",count,id,name,price,desp);
System.out.println();
count++;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//5、关闭连接,释放资源
try {
if (rs!=null){
rs.close();
}
if (pstmt!=null){
pstmt.close();
}
if (conn!=null&&!conn.isClosed()){
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}

}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class GoodsQuery {
public static void main(String[] args) {
Command command=new PrepareQueryCommand();
command.execute();
}
}


写回答

1回答

好帮手慕阿慧

2020-11-23

同学你好,本次练习是查询价格在1500以上到3500以下的商品信息,并打印输出。同学贴的是3-2练习的代码。建议同学检查一下,将正确的代码贴出来。

祝学习愉快~

0

0 学习 · 16556 问题

查看课程