Files
nxxmdata/backend/create-simple-environment-schedule.js

121 lines
4.3 KiB
JavaScript
Raw Normal View History

const mysql = require('mysql2/promise');
// 数据库配置
const dbConfig = {
host: process.env.DB_HOST || 'localhost',
port: process.env.DB_PORT || 3306,
user: process.env.DB_USER || 'root',
password: process.env.DB_PASSWORD || '',
database: process.env.DB_NAME || 'nxxmdata'
};
async function createEnvironmentScheduleTable() {
let connection;
try {
// 创建数据库连接
connection = await mysql.createConnection(dbConfig);
console.log('数据库连接成功');
// 创建环境监测时刻表
const createTableSQL = `
CREATE TABLE IF NOT EXISTS environment_schedules (
id INT AUTO_INCREMENT PRIMARY KEY,
farm_id INT NOT NULL COMMENT '农场ID',
device_id INT NOT NULL COMMENT '设备ID',
schedule_time TIME NOT NULL COMMENT '监测时刻HH:MM:SS',
temperature DECIMAL(5,2) NULL COMMENT '温度值(摄氏度)',
humidity DECIMAL(5,2) NULL COMMENT '湿度值(百分比)',
monitoring_date DATE NOT NULL DEFAULT (CURRENT_DATE) COMMENT '监测日期',
status ENUM('active', 'inactive', 'maintenance') DEFAULT 'active' COMMENT '监测状态',
notes TEXT NULL COMMENT '备注信息',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_farm_date_time (farm_id, monitoring_date, schedule_time),
INDEX idx_device (device_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='环境监测时刻表';
`;
await connection.execute(createTableSQL);
console.log('环境监测时刻表创建成功');
// 生成示例数据
const schedules = [
'06:00:00', '08:00:00', '10:00:00', '12:00:00',
'14:00:00', '16:00:00', '18:00:00', '20:00:00'
];
const insertSQL = `
INSERT INTO environment_schedules
(farm_id, device_id, schedule_time, temperature, humidity, monitoring_date, status, notes)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`;
let totalInserted = 0;
const today = new Date();
// 为过去7天生成数据
for (let day = 0; day < 7; day++) {
const monitoringDate = new Date(today);
monitoringDate.setDate(today.getDate() - day);
const dateStr = monitoringDate.toISOString().split('T')[0];
for (const time of schedules) {
// 农场1的数据
const temp1 = (18 + Math.random() * 15).toFixed(2);
const humidity1 = (45 + Math.random() * 35).toFixed(2);
await connection.execute(insertSQL, [
1, 1, time, temp1, humidity1, dateStr, 'active', `定时监测数据 - ${time}`
]);
totalInserted++;
// 农场2的数据
const temp2 = (16 + Math.random() * 18).toFixed(2);
const humidity2 = (40 + Math.random() * 40).toFixed(2);
await connection.execute(insertSQL, [
2, 2, time, temp2, humidity2, dateStr, 'active', `定时监测数据 - ${time}`
]);
totalInserted++;
}
}
console.log(`成功插入 ${totalInserted} 条环境监测时刻数据`);
// 验证数据
const [countResult] = await connection.execute(
'SELECT COUNT(*) as total FROM environment_schedules'
);
console.log(`环境监测时刻表总记录数: ${countResult[0].total}`);
const [todayResult] = await connection.execute(
'SELECT COUNT(*) as today_count FROM environment_schedules WHERE monitoring_date = CURDATE()'
);
console.log(`今日监测记录数: ${todayResult[0].today_count}`);
// 显示部分数据样例
const [sampleData] = await connection.execute(`
SELECT monitoring_date, schedule_time, temperature, humidity
FROM environment_schedules
ORDER BY monitoring_date DESC, schedule_time ASC
LIMIT 5
`);
console.log('\n数据样例:');
sampleData.forEach(record => {
console.log(`日期: ${record.monitoring_date}, 时间: ${record.schedule_time}, 温度: ${record.temperature}°C, 湿度: ${record.humidity}%`);
});
} catch (error) {
console.error('创建环境监测时刻表失败:', error.message);
} finally {
if (connection) {
await connection.end();
console.log('数据库连接已关闭');
}
}
}
// 执行创建操作
createEnvironmentScheduleTable();