使用Java编写的示例代码,将采集到的数据保存到MySQL数据库,并实现实时分析和查询最新的设备状态和预警信息。请注意,以下代码仅提供一个简单的框架,你可能需要根据实际需求进行修改和完善。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
public class DeviceDataStorage {
private Connection conn;
public DeviceDataStorage() {
// 初始化数据库连接
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/device_data";
String username = "your_username";
String password = "your_password";
conn = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
public void saveData(String deviceId, float temperature, float humidity, String status, String alert) {
// 将采集到的数据保存到数据库
String sql = "INSERT INTO device_data (device_id, temperature, humidity, status, alert, timestamp) VALUES (?, ?, ?, ?, ?, NOW())";
try {
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceId);
stmt.setFloat(2, temperature);
stmt.setFloat(3, humidity);
stmt.setString(4, status);
stmt.setString(5, alert);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void analyzeData() {
// 实时分析数据
String sql = "SELECT * FROM device_data WHERE timestamp >= ? ORDER BY timestamp DESC";
try {
PreparedStatement stmt = conn.prepareStatement(sql);
// 获取当前时间戳
Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
// 设置查询起始时间(例如,查询过去一小时内的数据)
stmt.setTimestamp(1, new Timestamp(currentTimestamp.getTime() - 3600 * 1000));
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
// 处理查询结果
String deviceId = rs.getString("device_id");
float temperature = rs.getFloat("temperature");
float humidity = rs.getFloat("humidity");
String status = rs.getString("status");
String alert = rs.getString("alert");
// TODO: 根据实际需求进行处理
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void queryLatestStatus(String deviceId) {
// 查询最新的设备状态和预警信息
String sql = "SELECT * FROM device_data WHERE device_id = ? ORDER BY timestamp DESC LIMIT 1";
try {
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceId);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
// 处理查询结果
float temperature = rs.getFloat("temperature");
float humidity = rs.getFloat("humidity");
String status = rs.getString("status");
String alert = rs.getString("alert");
// TODO: 根据实际需求进行处理
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
DeviceDataStorage storage = new DeviceDataStorage();
// 采集到的数据
String deviceId = "device_id";
float temperature = 25.5f;
float humidity = 60.0f;
String status = "正常";
String alert = "无";
// 保存数据到数据库
storage.saveData(deviceId, temperature, humidity, status, alert);
// 实时分析数据
storage.analyzeData();
// 查询最新的设备状态和预警信息
storage.queryLatestStatus(deviceId);
}
}
请注意,以上代码仅为示例,需要根据你实际的数据库配置和需求进行修改。另外,这里选取了MySQL作为数据库存储方式,你也可以选择其他合适的数据库,如Oracle、MongoDB等。