mysql2
安装依赖
npm install mysql2 express js-yaml
- mysql2 用来连接mysql和编写sq语句
- express 用来提供接口 增删改差
- js-yaml 用来编写配置文件
写代码:
//db.config.yaml db: host: localhost #主机 port: 3306 #端口 user: root #账号 password: '123456' #密码 一定要字符串 database: zxd # 库
index.js
import mysql2 from "mysql2/promise";
import fs from "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);
});
// 查询某个用户 (两种风格写法 1.${} 2.?+[])
app.get("/user/:id", async (req, res) => {
// await sql.query(`SELECT * FROM user WHERE id = ${req.params.id}`);
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, hobby } = req.body;
await sql.query(`insert into user(name,age,hobby) values(?,?,?)`, [
name,
age,
hobby,
]);
res.send({ ok: 1 });
});
// 更新用户
app.post("/update", async (req, res) => {
const { id, name, age, hobby } = req.body;
await sql.query("update user set name=?,age=?,hobby=?where id =?", [
name,
age,
hobby,
id,
]);
res.send({ ok: 1 });
});
// 删除用户
app.post("/delete", async (req, res) => {
const { id } = req.body;
await sql.query("delete from user where id = ?", [id]);
res.send({ ok: 1 });
});
const port = 3000;
app.listen(port, () => {
console.log("Server is running on port 3000");
});
index.http
GET http://localhost:3000/ HTTP/1.1 # GET http://localhost:3000/user/1 HTTP/1.1 # POST http://localhost:3000/create HTTP/1.1 # Content-Type: application/json # { # "name": "John Doe", # "hobby": "Coding", # "age": 30 # } # POST http://localhost:3000/update HTTP/1.1 # Content-Type: application/json # { # "id":1, # "name": "John Doe", # "age": 8 # } # POST http://localhost:3000/delete HTTP/1.1 # Content-Type: application/json # { # "id":1 # }