// 更新products表结构,添加联系人相关字段 const mysql = require('mysql2/promise'); async function updateProductTable() { let connection; try { // 连接数据库 - 使用正确的密码 connection = await mysql.createConnection({ host: '1.95.162.61', port: 3306, user: 'root', password: 'schl@2025', // 从.env文件中获取的密码 database: 'wechat_app' }); console.log('✅ 数据库连接成功'); // 检查product_contact字段是否存在 const [rows] = await connection.query( "SELECT column_name FROM information_schema.columns WHERE table_schema = 'wechat_app' AND table_name = 'products' AND column_name = 'product_contact'" ); if (rows.length === 0) { // 添加product_contact字段 await connection.query("ALTER TABLE products ADD COLUMN product_contact VARCHAR(100) DEFAULT ''"); console.log('✅ 已添加product_contact字段'); } else { console.log('ℹ️ product_contact字段已存在'); } // 检查contact_phone字段是否存在 const [phoneRows] = await connection.query( "SELECT column_name FROM information_schema.columns WHERE table_schema = 'wechat_app' AND table_name = 'products' AND column_name = 'contact_phone'" ); if (phoneRows.length === 0) { // 添加contact_phone字段 await connection.query("ALTER TABLE products ADD COLUMN contact_phone VARCHAR(20) DEFAULT ''"); console.log('✅ 已添加contact_phone字段'); } else { console.log('ℹ️ contact_phone字段已存在'); } // 查询所有已发布商品的数量 const [productRows] = await connection.query( "SELECT COUNT(*) as count FROM products WHERE status = 'published'" ); console.log(`📊 已发布商品数量: ${productRows[0].count}`); // 查询需要更新联系人信息的商品数量 const [pendingRows] = await connection.query( "SELECT COUNT(*) as count FROM products WHERE status = 'published' AND (product_contact = '' OR product_contact IS NULL OR contact_phone = '' OR contact_phone IS NULL)" ); console.log(`⚠️ 需要更新联系人信息的商品数量: ${pendingRows[0].count}`); // 显示一些商品数据作为示例 const [sampleProducts] = await connection.query( "SELECT productId, productName, product_contact, contact_phone FROM products WHERE status = 'published' LIMIT 5" ); console.log('\n📋 示例商品数据:'); sampleProducts.forEach(product => { console.log(`- ${product.productName}: 联系人=${product.product_contact || '空'}, 电话=${product.contact_phone || '空'}`); }); } catch (error) { console.error('❌ 操作失败:', error.message); } finally { if (connection) { await connection.end(); console.log('\n✅ 数据库连接已关闭'); } } } // 执行更新 updateProductTable();