nodejs连接数据库

-- 安装mysql模块

npm i mysql

 -连接数据库

const mysql = require('mysql')
//建立与mysql数据库的连接关系
const db = mysql.createPool({
    host:'127.0.0.1',//数据库的ip地址
    user:'root',//登录数据库的账号
    password:'1234',//登录数据库的密码
    database:'my_db_01'//指定要操作那个数据库
})
//测试mysql模块能否正常工作
db.query('SELECT 1',(err,res)=>{
    //报错
    if(err) return console.log('err.message :>> ', err.message);
    //正常
    console.log(res);
})

MySQL8可能会报错:

 ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client

 

 原因是最新的mysql模块并未完全支持MySQL 8的“caching_sha2_password”加密方式,而“caching_sha2_password”在MySQL 8中是默认的加密方式。

解决办法:

在数据库中新建查询运行下面代码

 ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
 // 'password'是你的数据库密码

 

试一试问题是否解决,执行sql语句

const sqlStr = 'select * from users'
db.query(sqlStr,(err,result)=>{
    if(err) return console.log('err.message :>> ', err.message);
    console.log(result);
})

结果.jpg

 

 成功解决!

 

posted @ 2022-02-23 14:17  初生土豆  阅读(149)  评论(0编辑  收藏  举报