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.
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 mysql = require ( 'mysql2' ) ;
require ( 'dotenv' ) . config ( ) ;
// 创建数据库连接池
// 连接池可以复用连接,提高性能
const pool = mysql . createPool ( {
host : process . env . DB _HOST || 'localhost' , // 数据库服务器地址
user : process . env . DB _USER || 'root' , // 数据库用户名
password : process . env . DB _PASSWORD || '' , // 数据库密码
database : process . env . DB _NAME || 'restaurant_db' , // 数据库名称
waitForConnections : true , // 等待可用连接
connectionLimit : 10 , // 最大连接数
queueLimit : 0 , // 队列限制( 0表示无限制)
charset : 'utf8mb4' // 字符集( 支持中文和emoji)
} ) ;
// 将连接池转换为Promise版本, 便于使用async/await
const promisePool = pool . promise ( ) ;
// 测试数据库连接
const testConnection = async ( ) => {
try {
const connection = await promisePool . getConnection ( ) ;
console . log ( '✅ 数据库连接成功!' ) ;
connection . release ( ) ; // 释放连接回连接池
return true ;
} catch ( error ) {
console . error ( '❌ 数据库连接失败:' , error . message ) ;
return false ;
}
} ;
// 导出连接池供其他模块使用
module . exports = {
pool : promisePool ,
testConnection
} ;