栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

Nodejs连接mysql数据库

Nodejs连接mysql数据库

创建数据库myprogram,在该数据库下创建表user
CREATE TABLE `myprogram`.`user` (
  `id` INT NOT NULL,
  `pwd` VARCHAr(45) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NOT NULL,
  `phone` VARCHAr(45) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `id_UNIQUE` (`id` ASC) VISIBLE,
  UNIQUE INDEX `pwd_UNIQUE` (`pwd` ASC) VISIBLE,
  UNIQUE INDEX `phone_UNIQUE` (`phone` ASC) VISIBLE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COMMENT = '用于用户注册登录';
INSERT INTO `myprogram`.`user` (`id`, `pwd`, `phone`) VALUES ('12306', '1234', '17777777777');
进行nodejs项目初始化

新建一个文件夹内建有index.js

使用终端在该文件夹目录下输入:npm init -y

初始化后可以发现该文件目录下会生成一个package.json

导入mysql模块:npm install mysql

随后编写index.js代码如下:

const mysql = require('mysql');
//创建连接对象
const connection = mysql.createConnection({
    host:'localhost',
    user:'root',
    password:'1234',
    port:3306,
    database:'myprogram'
});
//开始连接
connection.connect();
//执行 sql 语句
const sql = 'select * from user';
connection.query(sql, (err, result) => {
    if (err){
        console.error('error', err);
        return;
    }
    console.log('result', result);
})
//关闭连接
connection.end();

其中connection内的root为你的数据库user名,1234为数据库密码,3306为数据库端口号,myprogram为所连接的数据库。

在该目录下终端输入:node index.js就能运行啦~

遇到的问题

node链接mysql报错error:如下:error Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
    at Handshake.Sequence._packetToError (D:文件Nodejs学习mysql-demonode_modul~~~

后面还有一大串,总之就是说我的MySQL不兼容。

原因:这里我使用的是mysql8.0版本,mysql8.0密码认证采用了新的密码格式

解决办法:在mysql终端输入下面命令

//1234 是数据库账户密码,root数据库账户名
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '1234';

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/285667.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号