如何使用Node.js连接数据库

120 阅读1分钟
  1. 先下载安装mySql
  2. 下载安装navicat
  • 新建连接
  • 输入安装mysql时的用户名和密码 root root123 (这里是我自己的)
  1. 项目中安装 mysql包 pnpm add mysql -S

node中代码如下:

const mysql = require('mysql'); // 配置数据库连接参数 
const connection = mysql.createConnection({
host: 'localhost', // 数据库地址 
user: 'root', // 数据库用户名
password: '123456', // 数据库密码 
database: 'demo1', // 数据库名 }); 
// 开启数据库连接 connection.connect(function (error) {
if (error) throw error;
console.log('Successfully connected to the database.');
}); 
connection.query('select * from user', (err, results, filelds) => {
console.log(results); 
connection.end(); });

如果连接数据库出行以下报错 Failed to connect to MySQL database: Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client

原因:node提供的mysql包的版本不适配MYSQL8.0以上的版本,是因为8.0以上版本的MYSQL的授权方式改为了caching_sha2_password,需要将其改为mysql_native_password

  • 首先,登录到MySQL服务器,并使用以下命令查看用户的当前身份验证插件 (your_username your_host your_password均为你自己的数据库信息)
SELECT user, host, plugin FROM mysql.user WHERE user = 'your_username';

image.png

  • 然后,如果发现身份验证插件不是与你的客户端兼容的,你可以使用以下命令修改用户的身份验证插件
ALTER USER 'your_username'@'your_host' IDENTIFIED WITH mysql_native_password BY 'your_password';