Nodejs 第三十七章(mysql2)

在之前的篇章中,已经补充完成mysql的基本知识,那么现在开始,我们需要把mysqlexpress,nodejs连接起来。

安装依赖

sh 复制代码
npm install mysql2 express js-yaml
  1. mysql2 用来连接mysql和编写sq语句
  2. express 用来提供接口 增删改差
  3. js-yaml 用来编写配置文件

编写代码

db.ocnfig.yaml

yaml 复制代码
db:
   host: localhost #主机
   port: 3306 #端口
   user: root #账号
   password: '123456' #密码 一定要字符串
   database: xiaoman # 库

index.js

js 复制代码
import mysql2 from 'mysql2/promise';
import express from 'express';
import jsYaml from 'js-yaml'
import fs from 'node:fs'
const yamlInfo = fs.readFileSync('./db.config.yaml')
const config = jsYaml.load(yamlInfo)
const sql = await mysql2.createConnection({
    ...config.db
});

const app = express();
app.use(express.json());
//查询全部
app.get('/', async (req, res) => {
    const [rows] = await sql.query('select * from user');
    res.send(rows)
})
//单个查询
app.get('/user/:id', async (req, res) => {
    const [rows] = await sql.query('select * from user where id = ?', [req.params.id]);
    res.send(rows)
})
//创建
app.post('/create', async (req, res) => {
    const { name, age, hobby } = req.body;
    const [rows] = await sql.query('insert into user (name, age, hobby) values (?, ?, ?)', [name, age, hobby]);
    res.send(rows)
})
//更新
app.post('/update', async (req, res) => {
    const { id, name, age, hobby } = req.body;
    const [rows] = await sql.query('update user set name = ?, age = ?,hobby = ? where id = ?', [name, age, hobby, id]);
    res.send(rows)
})


const port = 3000;
app.listen(port, () => {
    console.log(`server is running at http://localhost:${port}`);
})

index.http

方便测试接口

http 复制代码
# 查询全部
 GET http://localhost:3000/ HTTP/1.1

# 单个查询
GET http://localhost:3000/user/2 HTTP/1.1

# 添加数据
POST http://localhost:3000/create HTTP/1.1
Content-Type: application/json

{
    "name":"张三",
    "age":18
}

# 更新数据
POST http://localhost:3000/update HTTP/1.1
Content-Type: application/json

{
    "name":"法外狂徒",
    "age":20,
    "id":23
}

后续更新计划

相关推荐
太平洋月光3 分钟前
MJML邮件如何随宽度变化动态切换有几列📮
前端·css
AAA不会前端开发5 分钟前
TypeScript核心类型系统完全指南
前端·typescript
徐同保8 分钟前
使用GitKraken把feature_xtb_1104分支的多次提交记录合并到一起,只保留一次提交记录,并合并到master分支
前端
小光学长17 分钟前
基于Vue的智慧楼宇报修平台设计与实现066z15wb(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
前端·数据库·vue.js
醉方休24 分钟前
web前端 DSL转换技术
前端
sen_shan25 分钟前
Vue3+Vite+TypeScript+Element Plus开发-27.表格页码自定义
前端·javascript·typescript
刺客_Andy33 分钟前
React 第五十二节 Router中 useResolvedPath使用详解和注意事项示例
前端·react.js·架构
豆浆94541 分钟前
vue3+qiankun主应用和微应用的路由跳转返回
前端
王将近1 小时前
Cesium 山洪流体模拟
前端·cesium
小时前端1 小时前
当循环遇上异步:如何避免 JavaScript 中最常见的性能陷阱?
前端·javascript