Files
jiebanke/create-database-simple.js
2025-08-30 14:33:49 +08:00

103 lines
2.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const mysql = require('mysql2');
// 数据库配置
const configs = [
{
name: '测试环境',
host: '192.168.0.240',
port: 3306,
user: 'root',
password: 'aiot$Aiot123'
},
{
name: '生产环境',
host: '129.211.213.226',
port: 9527,
user: 'root',
password: 'aiotAiot123!'
}
];
// 简单的SQL语句避免编码问题
const sqlStatements = [
"CREATE DATABASE IF NOT EXISTS jiebandata CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
"USE jiebandata",
`CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
openid VARCHAR(64) UNIQUE NOT NULL,
nickname VARCHAR(50) NOT NULL,
avatar VARCHAR(255),
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB`
];
function executeSQL(connection, sql, description) {
return new Promise((resolve, reject) => {
console.log(description);
connection.query(sql, (err, results) => {
if (err) {
console.error('失败:', err.message);
reject(err);
} else {
console.log('成功');
resolve(results);
}
});
});
}
async function setupDatabase(config) {
console.log(`\n开始设置 ${config.name} 数据库...`);
const connection = mysql.createConnection({
host: config.host,
port: config.port,
user: config.user,
password: config.password
});
try {
await new Promise((resolve, reject) => {
connection.connect((err) => {
if (err) reject(err);
else resolve();
});
});
for (let i = 0; i < sqlStatements.length; i++) {
await executeSQL(connection, sqlStatements[i], `执行SQL ${i + 1}/${sqlStatements.length}`);
}
console.log('✅ 数据库设置完成');
return true;
} catch (error) {
console.error('❌ 数据库设置失败:', error.message);
return false;
} finally {
connection.end();
}
}
async function main() {
console.log('🎯 结伴客数据库初始化');
console.log('='.repeat(50));
let successCount = 0;
for (const config of configs) {
const success = await setupDatabase(config);
if (success) successCount++;
console.log('\n' + '='.repeat(50));
}
console.log(`📊 完成: ${successCount}/${configs.length} 个环境成功`);
if (successCount > 0) {
console.log('\n🎉 数据库初始化完成!');
console.log('现在可以运行测试脚本来验证数据库结构。');
}
}
main().catch(console.error);