在 Node.js 中连接 MySQL 数据库时,你需要安装一个适当的 MySQL 驱动程序。一种常用的驱动程序是 mysql2,它是 mysql 模块的升级版本,提供更好的性能和支持。

以下是如何安装 mysql2 的步骤:

步骤 1: 初始化 Node.js 项目

首先,确保你的项目目录中有 package.json 文件。如果没有,可以通过以下命令初始化一个新的 Node.js 项目:
npm init -y

步骤 2: 安装 mysql2 模块

在终端中执行以下命令安装 mysql2:
npm install mysql2

步骤 3: 在代码中使用 mysql2

在你的 Node.js 代码中,引入 mysql2 模块并使用它来连接 MySQL 数据库。以下是一个简单的例子:
const mysql = require('mysql2');

// 创建数据库连接池
const pool = mysql.createPool({
  host: 'your_database_host',
  user: 'your_database_user',
  password: 'your_database_password',
  database: 'your_database_name',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 获取连接
pool.getConnection((err, connection) => {
  if (err) {
    console.error('Error getting connection: ' + err.message);
  } else {
    console.log('Connected to the database');

    // 释放连接
    connection.release();
  }
});

// 关闭连接池
pool.end(err => {
  if (err) {
    console.error('Error closing the database connection pool: ' + err.message);
  } else {
    console.log('Database connection pool closed');
  }
});

替换 your_database_host、your_database_user、your_database_password 和 your_database_name 分别为你的数据库的主机、用户名、密码和数据库名。

以上是使用 mysql2 连接 MySQL 数据库的基本步骤。根据实际需要,你可以使用 pool.query() 执行查询,处理结果等。


转载请注明出处:http://www.zyzy.cn/article/detail/8032/MySQL