const sqlite3 = require('sqlite3').verbose(); const path = require('path'); // SQLite数据库文件路径 const dbPath = path.join(__dirname, 'environment_schedule.db'); async function createEnvironmentScheduleTable() { return new Promise((resolve, reject) => { // 创建或连接到SQLite数据库 const db = new sqlite3.Database(dbPath, (err) => { if (err) { console.error('数据库连接失败:', err.message); reject(err); return; } console.log('SQLite数据库连接成功'); }); // 创建环境监测时刻表 const createTableSQL = ` CREATE TABLE IF NOT EXISTS environment_schedules ( id INTEGER PRIMARY KEY AUTOINCREMENT, farm_id INTEGER NOT NULL, device_id INTEGER NOT NULL, schedule_time TEXT NOT NULL, temperature REAL, humidity REAL, monitoring_date TEXT NOT NULL, status TEXT DEFAULT 'active', notes TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `; db.run(createTableSQL, (err) => { if (err) { console.error('创建表失败:', err.message); reject(err); return; } 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(); const insertPromises = []; // 为过去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); insertPromises.push(new Promise((resolve, reject) => { db.run(insertSQL, [ 1, 1, time, temp1, humidity1, dateStr, 'active', `定时监测数据 - ${time}` ], function(err) { if (err) reject(err); else { totalInserted++; resolve(); } }); })); // 农场2的数据 const temp2 = (16 + Math.random() * 18).toFixed(2); const humidity2 = (40 + Math.random() * 40).toFixed(2); insertPromises.push(new Promise((resolve, reject) => { db.run(insertSQL, [ 2, 2, time, temp2, humidity2, dateStr, 'active', `定时监测数据 - ${time}` ], function(err) { if (err) reject(err); else { totalInserted++; resolve(); } }); })); } } // 等待所有插入操作完成 Promise.all(insertPromises) .then(() => { console.log(`成功插入 ${totalInserted} 条环境监测时刻数据`); // 验证数据 db.get('SELECT COUNT(*) as total FROM environment_schedules', (err, row) => { if (err) { console.error('查询总数失败:', err.message); } else { console.log(`环境监测时刻表总记录数: ${row.total}`); } // 查询今日数据 const todayStr = today.toISOString().split('T')[0]; db.get( 'SELECT COUNT(*) as today_count FROM environment_schedules WHERE monitoring_date = ?', [todayStr], (err, row) => { if (err) { console.error('查询今日数据失败:', err.message); } else { console.log(`今日监测记录数: ${row.today_count}`); } // 显示部分数据样例 db.all(` SELECT monitoring_date, schedule_time, temperature, humidity FROM environment_schedules ORDER BY monitoring_date DESC, schedule_time ASC LIMIT 5 `, (err, rows) => { if (err) { console.error('查询样例数据失败:', err.message); } else { console.log('\n数据样例:'); rows.forEach(record => { console.log(`日期: ${record.monitoring_date}, 时间: ${record.schedule_time}, 温度: ${record.temperature}°C, 湿度: ${record.humidity}%`); }); } // 关闭数据库连接 db.close((err) => { if (err) { console.error('关闭数据库失败:', err.message); } else { console.log('数据库连接已关闭'); } resolve(); }); }); } ); }); }) .catch((err) => { console.error('插入数据失败:', err.message); reject(err); }); }); }); } // 执行创建操作 createEnvironmentScheduleTable() .then(() => { console.log('环境监测时刻表创建完成'); }) .catch((err) => { console.error('操作失败:', err.message); });