網站代碼開發(fā)文檔模板媒體:北京不再公布各區(qū)疫情數(shù)據
前言
前面我們已經介紹了第二階段的第1-4點內容,本篇介紹第5點內容:數(shù)據庫集成(koa+mysql)
也是第二階段內容的完結。
一、學習目標
在koa項目中正常連接數(shù)據庫,對數(shù)據表進行增刪改查的操作。
二、操作步驟
本篇文章會使用到:koa+sequelize+mysql+apipost(用于測試http方法)
注意:文章很多的操作步驟和“express框架的數(shù)據庫集成”基本上是一樣的,參考文章:
【express-generator】09-連接和使用數(shù)據庫-CRUD 操作(第二階段完結)-CSDN博客
所以文章中會簡單跳過/省略一些簡單的步驟。
1、安排依賴
在項目根目錄下運行以下命令安裝必要的依賴:
npm install koa mysql2 sequelize koa-router koa-bodyparser
?2、配置數(shù)據庫連接
注意:每個人的數(shù)據庫連接連接信息不一樣,對應修改自己的信息。
在state2/models/dbConnect.js
中配置數(shù)據庫連接信息:
// 該文件負責連接數(shù)據庫
const { Sequelize } = require("sequelize");// 創(chuàng)建數(shù)據庫連接
const sequelize = new Sequelize("mysite2", "root", "123456aa", {host: "localhost",dialect: 'mysql',logging: false
});const startDB=async()=> {try {await sequelize.authenticate();console.log('數(shù)據庫已建立起連接.');} catch (error) {console.error('Unable to connect to the database:', error);}
}
startDB()// 向外暴露這個連接實例
module.exports = sequelize;
3、定義數(shù)據模型
在state2/models/userModel寫入以下代碼:
const { DataTypes } = require("sequelize");
const sequelize = require("./dbConnect");// 定義數(shù)據模型
module.exports = sequelize.define("koauser", {// 這張表擁有哪些字段name : {type : DataTypes.STRING,allowNull : true},age : {type : DataTypes.INTEGER,allowNull : true},
},{//與模型定義時的名稱一致。 // 比如定義了上述定義了content模型,設置了這個字段,創(chuàng)建表的名字也是content。freezeTableName : true, //用于記錄數(shù)據的創(chuàng)建時間和更新時間。createdAt : false, updatedAt : false
});
這里我們定義了一個名為“koauser”的數(shù)據表,有name和age字段,分別是string和integer數(shù)據類型。?
4、初始化Sequelize和加載模型
在state2/demodels/db.js寫入以下代碼:
// 該文件負責對數(shù)據庫進行一個初始化操作
const sequelize = require("./dbConnect"); // 數(shù)據庫連接實例const userModel = require("./userModel"); // 數(shù)據模型
const initData=async function () {// 將數(shù)據模型和表進行同步await sequelize.sync({alter: true,})// 同步完成之后,有一些表是需要一些初始化數(shù)據// 查詢這張表有沒有內容,沒有內容才初始化數(shù)據const userCount = await userModel.count();if (!userCount) {// 進入此 if,說明該表沒有數(shù)據,我們進行一個初始化await userModel.create({name: "Tom",age:18})console.log("初始化內容數(shù)據表數(shù)據完畢...");}console.log("數(shù)據庫數(shù)據已經準備完畢....");
}
initData()
5、創(chuàng)建Koa應用并集成Sequelize
在state2/demo5.js中寫入以下代碼:
const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
// const models = require('./models');
const userModel = require('./models/userModel');
const app = new Koa();
const router = new Router();require('./models/db');
// 使用bodyParser中間件解析請求體
app.use(bodyParser());// 定義路由
router.get('/', async (ctx) => {ctx.body = 'Welcome to Koa with Sequelize!';
});// 使用路由中間件
app.use(router.routes()).use(router.allowedMethods());app.listen(3000, () => {console.log('Server is running at http://localhost:3000');
});
啟動服務,看是否正常連接數(shù)據庫和創(chuàng)建、初始化數(shù)據表。?
在state2的目錄下打開終端,執(zhí)行node demo5.js
啟動之前,數(shù)據庫的表情況?
啟動之后,多了一個koauser的數(shù)據表,并且有一條數(shù)據。
6、增刪改查(CRUD)操作
Create:增加
Read:查
Update:更新
Delete:刪除
6.1、查找所有用戶信息
在state2/demo5.js中新增代碼:
// 查找所有用戶
router.get('/users', async (ctx) => {const users = await userModel.findAll();ctx.body = users;
});
方法放在這個位置
測試:啟動服務+apipost工具
新增get方法,點擊發(fā)送則會得到以下結果
6.2、 增加新的用戶
// 創(chuàng)建用戶
router.post('/user', async (ctx) => {const { name, age } = ctx.request.body;try {const user = await userModel.create({ name,age });ctx.body = user;} catch (error) {ctx.status = 400;ctx.body = { error: error.message };}
});
測試:啟動服務+添加post方法
?在數(shù)據表中刷新可以看到新增的數(shù)據項
6.3、查找單條用戶數(shù)據
為了后續(xù)測試,先增加了幾條數(shù)據
?
// 查找單個用戶
router.get('/user/:id', async (ctx) => {const { id } = ctx.params;try {const user = await userModel.findByPk(id);if (user) {ctx.body = user;} else {ctx.status = 404;ctx.body = { error: 'User not found' };}} catch (error) {ctx.status = 400;ctx.body = { error: error.message };}
});
測試:啟動服務+添加get方法
查找id為1的數(shù)據項
查找id為3的數(shù)據項
?6.4、更新用戶信息
// 更新用戶router.put('/user/:id', async (ctx) => {const { id } = ctx.params;const { name,age } = ctx.request.body;try {const user = await userModel.findByPk(id);if (user) {await user.update({ name,age });ctx.body = user;} else {ctx.status = 404;ctx.body = { error: 'User not found' };}} catch (error) {ctx.status = 400;ctx.body = { error: error.message };}});
?測試:啟動服務+測試put方法
我們嘗試將id為1的數(shù)據項,對name進行修改成"Rura"(原本是Tom)
響應結果
?刷新數(shù)據表,可以看見id為1的數(shù)據項的name已經被修改。
6.5、刪除用戶信息
// 刪除用戶router.delete('/user/:id', async (ctx) => {const { id } = ctx.params;try {const user = await userModel.findByPk(id);if (user) {await user.destroy();ctx.status = 204;} else {ctx.status = 404;ctx.body = { error: 'User not found' };}} catch (error) {ctx.status = 500;ctx.body = { error: error.message };}});
測試:啟動服務+測試delete方法
這里我們嘗試將id為4的數(shù)據項進行刪除
點擊發(fā)送,在數(shù)據表中刷新查看結果。
三、小結
這篇我們介紹了在koa中如何使用數(shù)據庫,創(chuàng)建和初始化數(shù)據表,并介紹了數(shù)據表的常用操作:增刪改查,文章以“代碼示范+測試”的內容呈現(xiàn)。文章中用到的代碼示范,我已經同步更新在代碼倉庫中,有需要的朋友請自行獲取:koa練習: koa練習
歡迎大家star和fork,也歡迎一起完善這個代碼倉~
koa專欄的第二階段的內容到此結束,后續(xù)的文章我會更新第三階段的內容。
關注我,及時獲取最新文章消息~