跳至主要內容
Node.js 操作 MySQL(mysql2 实战)

1. 安装与连接

npm install mysql2
const mysql = require('mysql2/promise');  // 使用 Promise 版本(推荐)

// 连接配置(类似前端请求的 baseURL + 鉴权)
const pool = mysql.createPool({
    host: 'localhost',      // 数据库主机
    port: 3306,             // MySQL 默认端口
    user: 'root',           // 用户名
    password: '123456',     // 密码
    database: 'my_app',     // 数据库名
    waitForConnections: true,
    connectionLimit: 10,    // 连接池大小
    queueLimit: 0,
});

// 测试连接
async function testConnection() {
    try {
        const connection = await pool.getConnection();
        console.log('数据库连接成功 ✅');
        connection.release();
    } catch (err) {
        console.error('数据库连接失败 ❌', err);
    }
}

Mr.Ding大约 3 分钟mysqlNode.jsmysql2全栈前端转后端