来源:Node.js

后端需要操作数据库以便实现业务,在Nodejs中可以用mysql2连接和操作MySQL数据库、js-yaml可以用于操作yaml配置文件

1
pnpm install mysql2 express js-yaml

数据库配置

在db.config.yaml文件写入配置

1
2
3
4
5
6
db:
host: localhost #主机
port: 3306 #端口
user: CherikoM #账号
password: '114514' #密码是字符串
database: test # 库

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import mysql2 from 'mysql2/promise'
import fs from 'node:fs'
import jsyaml from 'js-yaml'
import express from 'express'

// 获取配置文件
const yaml = fs.readFileSync('./db.config.yaml', 'utf8')
const config = jsyaml.load(yaml)
const sql = await mysql2.createConnection({
...config.db
})

const app = express()
app.use(express.json())

// 查询全部数据
app.get('/',async (req,res)=>{
const [data] = await sql.query('select * from user')
res.send(data)
})

// 根据id查询
app.get('/user/:id',async (req,res)=>{
const [row] = await sql.query(`select * from user where id = ?`,[req.params.id])
res.send(row)
})

// 添加数据
app.post('/create',async (req,res)=>{
const {name,age,address} = req.body
await sql.query(`insert into user(name,age,address) values(?,?,?)`,[name,age,hobby])
res.send({ok:1})
})

// 更新数据
app.post('/update',async (req,res)=>{
const {name,age,address,id} = req.body
await sql.query(`update user set name = ?,age = ?,address = ? where id = ?`,[name,age,address,id])
res.send({ok:1})
})

// 删除数据
app.post('/delete',async (req,res)=>{
await sql.query(`delete from user where id = ?`,[req.body.id])
res.send({ok:1})
})

app.listen(11451, () => {
console.log(`Server on 11451`)
})