【笔记】Nodejs操作MySQL数据库
前言
Nodejs操作MySQL数据库
安装
1 | npm install mysql |
引入模块并配置
1 | const mysql = require("mysql"); |
查询数据
- 得到的results是一个数组,存放查询到的所有数据
<table>:需要查询的数据表
1 | db.query("SELECT * FTOM <table>", function (err, results) { |
新增数据
通过数组传递占位符参数
- 通过
?作为占位符,通过数组传递所有占位符的参数 - 通过
results.affactedRows受影响的行数,来判定SQL语句是否执行成功
1 | db.query("INSERT INTO <table> (id, name) VALUES (?, ?)", ["id", "name"], function (err, results) { |
通过对象传递占位符参数
- 通过
?作为占位符,通过对象传递SET子句的占位符参数
1 | db.query("INSERT INTO <table> SET ?", {"id": "", "name": ""}, function (err, results) { |
修改数据
通过数组传递占位符参数
1 | db.query("UPDATE <table> SET name=? WHERE id=?", ["name", "id"], function (err, results) { |
通过对象传递占位符参数
- 通过
?作为占位符,通过对象传递SET子句的占位符参数
1 | db.query("UPDATE <table> SET ? WHERE id=?", [{"name": ""}, "id"], function (err, results) { |
删除数据
直接传递占位符的参数
- 如果占位符只有1个,可以省略数组直接传递占位符的参数
1 | db.query("DELETE FROM <table> WHERE id=?", "id", function (err, results) { |
踩坑
- 报错:
ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
解决问题
- MySQL中修改认证方式为
mysql_native_password
1 | ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456'; |