diff --git a/back/src/config/mysql.js b/back/src/config/mysql.js new file mode 100644 index 0000000..2a043f4 --- /dev/null +++ b/back/src/config/mysql.js @@ -0,0 +1,53 @@ +const mysql = require('mysql2/promise'); + +// 从环境变量读取配置,支持默认值 // TODO +const MYSQL_HOST = '127.0.0.1'; +const MYSQL_PORT = 3306; +const MYSQL_USER = 'root'; +const MYSQL_PASSWORD = '123456'; +const MYSQL_DATABASE = 'cus'; + +// 创建连接池 +const pool = mysql.createPool({ + host: MYSQL_HOST, + port: MYSQL_PORT, + user: MYSQL_USER, + password: MYSQL_PASSWORD, + database: MYSQL_DATABASE, + waitForConnections: true, + connectionLimit: 10, // TODO + queueLimit: 0 +}); + +// 测试连接 // TODO +pool.getConnection() + .then((connection) => { + console.log('MySQL 连接成功'); // TODO + connection.release(); + }) + .catch((err) => { + console.error('MySQL 连接失败:', err); // TODO + }); + +// 执行查询 +async function query(sql, params) { + const [rows] = await pool.execute(sql, params); + return rows; +} + +// 获取连接 +async function getConnection() { + return pool.getConnection(); +} + +// 关闭连接池 +async function close() { + return pool.end(); +} + +// 导出方法 +module.exports = { + query, + getConnection, + close +}; \ No newline at end of file