From a6e6a13614e06206923e78e5d9110d1c5d2c3f5f Mon Sep 17 00:00:00 2001 From: luozhj33 Date: Thu, 19 Mar 2026 14:04:35 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20mysql=E5=92=8Credis=E8=BF=9E=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- back/src/config/mysql.js | 53 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 back/src/config/mysql.js 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