一、mysql
1.1 安装
window系统下载msi版按照向导安装Mysql,下载地址:https://pc.qq.com/detail/3/detail_1303.html,包含了mysql server,workbench等。
安装后打开mysql commain line工具,输入root密码登录。可通过命令行操作数据库。
或打开MySql Workbench连接本地数据库进行数据库的管理
1.2 准备数据
CREATE TABLE table_name (column_name column_type);
创建表
CREATE TABLE `user` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`age` tinyint DEFAULT NULL,
PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO table_name ( field1, field2,...fieldN ) VALUES( value1, value2,...valueN );
插入数据
INSERT INTO `user` (`id`, `name`, `age`)
VALUES
(1,'Mark',40),
(2,'Dell',33),
(3,'Timo',28);
二、express连接mysql
2.0 初始化项目
express hello-express
db目录为业务增加的数据库管理文件夹
2.1 安装mysql包
npm install mysql
2.2 准备mysql配置
db目录下创建command.js文件存放操作语句,代码如下:
const INSERT = 'INSERT INTO user (id, name, age) values (0, ?, ?)'
const SELECTALL = 'select * from my_users'
const SELECT = 'select * from my_users where id = ?'
const DELETE = 'delete from my_users where id = ?'
const UPDATE = 'update my_users set name=?, age=? where id=?'
module.exports = {
INSERT,
SELECTALL,
SELECT,
DELETE,
UPDATE
}
2.3 查询数据库
db目录增加sql.js,增加查询代码
const CONFIG = {
host: 'localhost',
port: 3306,
user: 'user',
password: 'user123',
database: 'mysql'
}
const mysql = require('mysql')
const pool = mysql.createPool(CONFIG)
const run = (command, params) => {
return new Promise((resolve, reject) => {
pool.getConnection((error, connection) => {
if(error) reject('mysql connection error')
console.log(command)
connection.query(command, params, (err, result) => {
err ? reject(err) : resolve(result)
})
})
})
}
module.exports = {
run
}
在routes/users.js增加路由响应
var express = require('express');
var router = express.Router();
var command = require('../db/command')
var mysql = require('../db/sql')
/* GET users listing. */
router.get('/', async (req, res, next) => {
try {
const result = await mysql.run(command.SELECTALL)
res.send(result)
} catch(err) {
res.status(500).send(err)
}
});
router.get('/:user_id', async (req, res, next) => {
try {
const id = req.params.user_id
const result = await mysql.run(command.SELECT, id)
res.send(result)
} catch(err) {
res.status(500).send(err)
}
});
module.exports = router;
浏览器访问http://localhost:3000/users则得到users串
浏览器访问http://localhost:3000/users/1则得到id为1的用户信息
三、Troubleshooting
1. 连接数据库出错
错误信息: Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
错误原因: 原因8.0mysql引入了caching_sha2_password模块作为默认身份验证插件,nodejs还没有跟进
解决方案:进入mysql命令行工具,执行下面命令
ALTER USER ‘userName’@'HostName' IDENTIFIED WITH mysql_native_password BY '自己的密码';
如: ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'admin123';
2. response发送响应时报错
错误信息: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
错误原因: send()发送后,next()又发送,重复发送请求。
解决方案:把next删除
或这种解决方案:https://www.cnblogs.com/codebook/p/10040501.html