【笔记】Nodejs的mysql模块学习笔记

前言

通过Nodejs的mysql模块操作Mysql数据库实现CRUD

安装

1
npm install mysql

引入模块并配置

1
2
3
4
5
6
7
const mysql = require("mysql");
const db = mysql.createPool({
host: "127.0.0.1",
user: "root",
password: "",
database: ""
});

查询数据

  • 得到的results是一个数组,存放查询到的所有数据

<table>:需要查询的数据表

1
2
3
4
db.query("SELECT * FTOM <table>", function (err, results) {
if (err) return console.log(err.message);
console.log(results);
});

新增数据

通过数组传递占位符参数

  • 通过?作为占位符,通过数组传递所有占位符的参数
  • 通过results.affactedRows受影响的行数,来判定SQL语句是否执行成功
1
2
3
4
db.query("INSERT INTO <table> (id, name) VALUES (?, ?)", ["id", "name"], function (err, results) {
if (err) return console.log(err.message);
if (results.affactedRows !== 0) console.log(results);
});

通过对象传递占位符参数

  • 通过?作为占位符,通过对象传递SET子句的占位符参数
1
2
3
4
db.query("INSERT INTO <table> SET ?", {"id": "", "name": ""}, function (err, results) {
if (err) return console.log(err.message);
if (results.affactedRows !== 0) console.log(results);
});

修改数据

通过数组传递占位符参数

1
2
3
4
db.query("UPDATE <table> SET name=? WHERE id=?", ["name", "id"], function (err, results) {
if (err) return console.log(err.message);
if (results.affactedRows !== 0) console.log(results);
});

通过对象传递占位符参数

  • 通过?作为占位符,通过对象传递SET子句的占位符参数
1
2
3
4
db.query("UPDATE <table> SET ? WHERE id=?", [{"name": ""}, "id"], function (err, results) {
if (err) return console.log(err.message);
if (results.affactedRows !== 0) console.log(results);
});

删除数据

直接传递占位符的参数

  • 如果占位符只有1个,可以省略数组直接传递占位符的参数
1
2
3
4
db.query("DELETE FROM <table> WHERE id=?", "id", function (err, results) {
if (err) return console.log(err.message);
if (results.affactedRows !== 0) console.log(results);
});

踩坑

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

解决问题

  • 在mysql中修改身份验证模式
1
2
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456';
FLUSH PRIVILEGES;

完成

参考文献

哔哩哔哩——黑马程序员
CSDN——默默花上开