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
}

后续更新计划

相关推荐
布列瑟农的星空5 分钟前
重学React——memo能防止Context的额外渲染吗
前端
FuckPatience5 分钟前
Vue 与.Net Core WebApi交互时路由初探
前端·javascript·vue.js
小小前端_我自坚强11 分钟前
前端踩坑指南 - 避免这些常见陷阱
前端·程序员·代码规范
lichenyang45312 分钟前
从零实现JSON与图片文件上传功能
前端
WebGirl15 分钟前
动态生成多层表头表格算法
前端·javascript
hywel40 分钟前
一开始只是想整理下书签,结果做成了一个 AI 插件 😂
前端
傅里叶43 分钟前
SchedulerBinding 的三个Frame回调
前端·flutter
小小前端_我自坚强1 小时前
React Hooks 使用详解
前端·react.js·redux
java水泥工1 小时前
基于Echarts+HTML5可视化数据大屏展示-车辆综合管控平台
前端·echarts·html5·大屏模版
独立开发者Pony1 小时前
【开源】假期爆肝我做了一个全新的Ai写小说工具模式
人工智能·开源·node.js