1 准备工作
1.再vscode中新建文件夹,右键文件夹选择**集成终端中打开**
2.输入初始化命令:`npm init -y`
3.安装express 模块:`npm i express`
4.安装mysql模块:`npm i mysql`
const express = require('express') //引入express 模块
const app = express() //创建实例
const mysql = require('mysql') //引入mysql 模块
// 创建数据库连接 填入数据库信息
//填自己数据库的信息!!!!!!!!!!!
const conn = mysql.createConnection({
user:'root', //用户名
password:'root', //密码
host:'localhost', //主机(默认都是local host)
database:'node' //数据库名
})
// 测试连接
conn.connect(err=>{
console.log(err,'如果为null 连接成功');
})
// 定义路由(说白了就是网址)
app.get('/a', (req, res) => {
// let sqlStr = "INSERT INTO user(name, pwd) VALUES ('sansan', '123456');"
// let sqlStr = "update user set name='sisi' where id=5";
let sqlStr = "select * from user where id ";
// let sqlStr = "delete from user where id=5 ";
插入多条数据
// const params =[
// ['小明',"11111"],['小雯',"22222"],['小华',"33333"]
// ];
// conn.query("INSERT INTO user(name, pwd) VALUES ?;",[params],(err, result) => {
// console.log(err, 'sql语句执行成功');
// // console.log(result);
// })
// 执行mysql 语句
conn.query(sqlStr, (err, result) => {
console.log(err, 'sql语句执行成功');
console.log(result);
res.json({code: 200, data: result, msg: '成功'})
})
//成功后的页面显示
// res.send('插入成功')
})
// 开启服务器
app.listen(3000, () => {
console.log('服务器在3000端口开启。。。。。');
})
报错信息显示为:
{
"code": "ER_NOT_SUPPORTED_AUTH_MODE",
"errno": 1251,
"sqlMessage": "Client does not support authentication protocol requested by server; consider upgrading MySQL client",
"sqlState": "08004",
"fatal": true
}
解决方案:
1、使用管理员运行命令提示符
2、进入到mysql安装目录的bin目录下默认安装路径大概是(C:\Program Files\MySQL\MySQL Server 8.0\bin)
3、在命令提示行中键入: mysql -u root -p
4、mysql> alter user 'root'@'localhost' identified with mysql_native_password by 'asd123456';此时得到提示Query OK, 0 rows affected (0.01 sec),这里是修改密码的认证方式
5、mysql> flush privileges;此时得到提示Query OK, 0 rows affected (0.01 sec),这里是重启权限
6、mysql> exit 退出mysql