You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

32 lines
1.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

const { Sequelize } = require('sequelize');
// 加载 .env 里的环境变量
require('dotenv').config();
// 创建 Sequelize 实例,连接 MySQL
const sequelize = new Sequelize(
process.env.DB_NAME, // 数据库名uniapp_db
process.env.DB_USER, // 账号root
process.env.DB_PASSWORD, // 密码(从 .env 读取就是123456
{
host: process.env.DB_HOST, // 主机localhost
port: process.env.DB_PORT, // 端口3306
dialect: 'mysql', // 数据库类型mysql
pool: { // 连接池(优化性能,不用改)
max: 5,
min: 0,
idle: 10000
},
logging: false // 关闭 SQL 日志(开发阶段想调试可以改成 true
}
);
// 测试数据库连接的函数
const testDbConnection = async () => {
try {
await sequelize.authenticate();
console.log('MySQL 数据库连接成功!');
} catch (error) {
console.error('数据库连接失败:', error);
process.exit(1); // 连接失败就退出进程,避免后续报错
}
};
// 导出实例和连接测试方法,供其他文件使用
module.exports = { sequelize, testDbConnection };