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