当前位置:网站首页>Koa2 connects to MySQL database to realize the operation of adding, deleting, changing and querying
Koa2 connects to MySQL database to realize the operation of adding, deleting, changing and querying
2022-07-19 10:22:00 【Ke Xiaonan】
Create project
install ko2 The scaffold :
$ npm install -g koa-generator
Create the project and initialize the dependencies :
$ koa2 -e kao2-demo
$ cd koa2-demo
$ npm install
Configure startup commands under different environment variables :
# install cross-env
$ npm install cross-env --save-dev
modify package.json file :
{
"scripts": {
"start": "node bin/www",
"dev": "cross-env NODE_ENV=dev ./node_modules/.bin/nodemon bin/www",
"prd": "cross-env NODE_ENV=production pm2 start bin/www",
"test": "echo \"Error: no test specified\" && exit 1"
}
}
Send a request
Process in routing file http request , With routes/index.js File as an example :
const router = require('koa-router')()
// get request
router.get('/profile/:username', async (ctx, next) => {
// Get dynamic parameters
const {
username } = ctx.params
// Respond to json data
ctx.body = {
title: 'this is profile page',
user: {
username
}
}
})
// post request
router.post('/login', async (ctx, next) => {
// obtain post Request parameters
const {
username, password } = ctx.request.body
ctx.body = {
code: 200,
msg: 'login success',
user: {
username,
password
}
}
})
module.exports = router
Use postman Send separately get and post Request test :
# get request
http://localhoost:3000/profile/tom
# post request
http://localhost:3000/login
mysql Use
Installation dependency :
$ npm install mysql2 sequelize --save
Connect to database :
// seq.js
const Sequelize = require('sequelize')
const conf = {
host: 'localhost',
dialect: 'mysql'
}
// Online environments use connection pools
// conf.pool = {
// max: 5, // The maximum number of connections in the connection pool
// min: 0, // The minimum number of connections in the connection pool
// idle: 10000, // A connection in 10s Not used within , Then release
// }
const seq = new Sequelize('datasets', 'root', 'root', conf)
module.exports = seq
Create connection :
// sync.js
const seq = require('./seq')
require('./model')
// Test connection
seq.authenticate().then(() => {
console.log('mysql ok')
}).catch(() => {
console.log('mysql no')
})
// Perform synchronization ,force by true Delete the old table and create a new table
seq.sync({
force: false }).then(() => {
console.log('sync ok')
process.exit()
})
Creating a data model :
// model.js
const Sequelize = require('sequelize')
const seq = require('./seq')
// establish Users Model
const Users = seq.define('users', {
id: {
type: Sequelize.INTEGER, // varchar(255)
allowNull: false, // Not empty
primaryKey: true, // Primary key
comment: ' user ID' // remarks
},
username: {
type: Sequelize.STRING,
},
pwd: {
type: Sequelize.STRING
},
nikename: {
type: Sequelize.STRING
}
})
// establish blog Model
const Blogs = seq.define('blogs', {
title: {
type: Sequelize.STRING,
allowNull: false
},
desc: {
type: Sequelize.STRING,
allowNull: false
},
content: {
type: Sequelize.TEXT, // Big text types
allowNull: false
},
userId: {
type: Sequelize.INTEGER,
allowNull: false
}
})
// Foreign key link
Blogs.belongsTo(Users, {
foreignKey: 'userId' // Create foreign keys Blogs.userId -> Users.id
})
Users.hasMany(Blogs, {
foreignKey: 'userId' // Create foreign keys Blogs.userId -> Users.id
})
// Blogs.belongsTo(Users)
module.exports = {
Users,
Blogs
}
insert data
// create.js
const {
Users } = require('./model')
!(async function() {
// Create user
const zhangsan = await Users.create({
id: '112',
username: ' Li Si ',
pwd: '123456',
nikename: 'hello'
})
console.log(' insert data :', zhangsan.dataValues)
})()
Query data
// select.js
const {
Blogs, Users } = require('./model')
!(async function() {
// Query a piece of data
const zhangsan = await Users.findOne({
where: {
username: ' Zhang San '
}
})
console.log(' Query a piece of data :', zhangsan.dataValues)
// Query specific columns
const names = await Users.findOne({
attributes: ['username', 'nikename']
})
console.log(' Query specific columns :', names.dataValues)
// Query list
const list = await Users.findAll({
where: {
id: 1
},
order: [
['id', 'desc'] // Descending
]
})
console.log(' Query all the data :', list.map(users => users.dataValues))
// Pagination
const pageList = await Users.findAll({
limit: 2, // Limit the number of queries this time ( Number of entries per page )
offset: 0, // How many ( The starting position )
order: [
['id', 'asc'] // Ascending
]
})
console.log(' Paging query :', pageList.map(users => users.dataValues))
// Total number of queries
const usersCount = await Users.findAndCountAll({
limit: 2, // Limit the number of queries this time ( Number of entries per page )
offset: 0, // How many ( The starting position )
order: [
['id', 'asc'] // Ascending
]
})
console.log(' Total number of queries :',
usersCount.count, // All totals , Do not consider paging
usersCount.rows.map(users => users.dataValues)
)
// Even the table query 1: adopt Blogs Inquire about Users
const blogListWithUser = await Blogs.findAndCountAll({
order: [
['id', 'desc']
],
include: [
{
model: Users,
attributes: ['username', 'nikename'],
where: {
username: ' Zhang San '
}
}
]
})
console.log(' Query results :',
blogListWithUser.count,
blogListWithUser.rows.map(blogs => {
const blogVals = blogs.dataValues
blogVals.user = blogVals.user.dataValues // many-to-one
return blogVals
})
)
// Even the table query 2: adopt Users Inquire about Blogs
const usersListWithBlogs = await Users.findAndCountAll({
attributes: ['username', 'nikename'],
include: [
{
model: Blogs
}
]
})
console.log(' Query results :',
usersListWithBlogs.count,
usersListWithBlogs.rows.map(users => {
const userVals = users.dataValues
userVals.blogs = userVals.blogs.map(blog => blog.dataValues) // One-to-many relation
return userVals
})
);
})()
Modifying data
// update.js
const {
Users } = require('./model')
!(async function() {
// Modify user information
const updateRes = await Users.update({
nikename: 'zhangsan' // Modified value
}, {
where: {
username: ' Zhang San ' // Conditions
}
})
console.log(' Modify the result :', updateRes[0] > 0)
})()
Delete data
// delete.js
const {
Users } = require('./model')
!(async function() {
// Delete a piece of data
const deleteRes = await Users.destroy({
where: {
id: 111
}
})
console.log(' Delete result :', deleteRes > 0)
})()
Fuzzy query
// select.js
const {
Blogs, Users } = require('./model')
const Op = require('sequelize').Op // You have to import
!(async function(keywords) {
// Paging query
const pageList = await Users.findAll({
limit: 2, // Limit the number of queries this time ( Number of entries per page )
offset: 0, // How many ( The starting position )
order: [
['id', 'asc'] // Ascending
],
where: {
// Query criteria
nikename: {
[Op.like]: `%${
keywords}%` // key word
},
id: '1234565'
}
})
console.log(' Paging query :', pageList.map(users => users.dataValues))
})()
边栏推荐
- 数据湖(十二):Spark3.1.2与Iceberg0.12.1整合
- opencv 画黑色矩形,并写上序号
- 完全背包问题代码模板
- Learning summary of MySQL advanced Chapter 11: locate SQL methods with slow execution and analyze the use of query statement explain
- 快速判断站点是否存活的 3 种编程实现
- 024.static与final使用陷阱 续
- 通信工程论文 通信网络中故障数据优化检测仿真研究
- 高性能IO框架库libevent(三):libevent框架函数概述
- FFmpeg录制视频、停止(VB.net,踩坑,类库——10)
- Flink entry to practice - stage 5 (processing function)
猜你喜欢

Relationship between standardization, normalization and regularization

标准化、归一化和正则化的关系

HCIA 静态综合实验报告 7.10

2022年全国最新消防设施操作员(中级消防设施操作员)模拟试题及答案

圆桌实录:炉边对话——如何在 Web3 实现创新

Kirin Xin'an operating system derivative solution | host security reinforcement software, to achieve one click rapid reinforcement!

【森城市】GIS数据漫谈(四)— 坐标系统

HCIA 静态基础实验 7.8

Pfsense configure tailscal site to site connection

Flink entry to practice - stage 5 (processing function)
随机推荐
一个简单的websocket例子
Microsoft OneNote 教程,如何在 OneNote 中插入数学公式?
高效理解 FreeSql WhereDynamicFilter,深入了解设计初衷[.NET ORM]
【Unity技术积累】实现鼠标画线功能 & LineRenderer
Analysis of Web Remote Code Execution Vulnerability of Zhongke panyun-d module
华为无线设备配置智能漫游
文华商品指数研究
idea展示服务端口--service
Network Security Learning (Qianfeng network security notes) 1-- building virtual machines
Flink entry to practice - stage 5 (processing function)
NJCTF 2017messager
机械臂速成小指南(零点五):机械臂相关资源
[Northeast Normal University] information sharing of postgraduate entrance examination and re examination
Date -- machine test topic for postgraduate entrance examination of Guizhou University
R语言dplyr包select函数删除dataframe数据中包含指定字符串内容的数据列(drop columns in dataframe)
string类的介绍及模拟实现
押注.NET 是件好事
Online education knowledge payment website source code system + live broadcast + applet, installation tutorial
快速判断站点是否存活的 3 种编程实现
Secondary vocational network security - (2022 network security NC batch connection script) free script oh~~~