有一个用电量表记录每天的用电量,字段为日期、设备编号、用电量,有一个Java实体 类对象,属性为今日用电量、昨日用电量、增量、今日较昨日增长率,写-条sq|,传 入设备编号、日期使结果能够映射到该对象
时间: 2024-01-01 18:06:51 浏览: 71
的属性上。
CREATE TABLE electricity_meter (
id INT PRIMARY KEY AUTO_INCREMENT,
device_number VARCHAR(20) NOT NULL,
date DATE NOT NULL,
power_consumption FLOAT NOT NULL
);
INSERT INTO electricity_meter (device_number, date, power_consumption)
VALUES ('device001', '2022-01-01', 100),
('device001', '2022-01-02', 120),
('device001', '2022-01-03', 150),
('device002', '2022-01-01', 80),
('device002', '2022-01-02', 90),
('device002', '2022-01-03', 100);
public class ElectricityUsage {
private float todayUsage;
private float yesterdayUsage;
private float increment;
private float growthRate;
public ElectricityUsage(float todayUsage, float yesterdayUsage, float increment, float growthRate) {
this.todayUsage = todayUsage;
this.yesterdayUsage = yesterdayUsage;
this.increment = increment;
this.growthRate = growthRate;
}
// getters and setters
}
public class ElectricityUsageCalculator {
public static ElectricityUsage calculateUsage(String deviceNumber, Date date) throws SQLException {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
PreparedStatement statement = connection.prepareStatement("SELECT power_consumption FROM electricity_meter WHERE device_number = ? AND date = ?");
statement.setString(1, deviceNumber);
statement.setDate(2, date);
ResultSet resultSet = statement.executeQuery();
float todayUsage = 0;
float yesterdayUsage = 0;
float increment = 0;
float growthRate = 0;
if (resultSet.next()) {
todayUsage = resultSet.getFloat("power_consumption");
}
statement.setDate(2, new Date(date.getTime() - 24 * 60 * 60 * 1000));
resultSet = statement.executeQuery();
if (resultSet.next()) {
yesterdayUsage = resultSet.getFloat("power_consumption");
}
increment = todayUsage - yesterdayUsage;
growthRate = (increment / yesterdayUsage) * 100;
return new ElectricityUsage(todayUsage, yesterdayUsage, increment, growthRate);
}
}
// Usage
String deviceNumber = "device001";
Date date = new Date();
try {
ElectricityUsage usage = ElectricityUsageCalculator.calculateUsage(deviceNumber, date);
System.out.println("Today usage: " + usage.getTodayUsage());
System.out.println("Yesterday usage: " + usage.getYesterdayUsage());
System.out.println("Increment: " + usage.getIncrement());
System.out.println("Growth rate: " + usage.getGrowthRate() + "%");
} catch (SQLException e) {
e.printStackTrace();
}
阅读全文