当前位置:网站首页>[Architect (Part 39)] connecting MySQL database developed by server
[Architect (Part 39)] connecting MySQL database developed by server
2022-06-22 09:09:00 【A tailed Warbler】
Keep creating , Accelerate growth ! This is my participation 「 Nuggets day new plan · 6 Yuegengwen challenge 」 Of the 22 God , Click to see the event details
Connect and create a new local database
open workbench , Click the button to connect to the database
Fill in the database name , Other defaults are fine
Click here to fill in the password
Fill in the password set during installation , And then click ok
Click to test the connection
Show successfully It's a success
Close the pop-up window , Click on ok
This is the database we just added , Click to see
Click this icon to add the database
Enter the database name , Choose the encoding , Click on apply
Continue clicking apply
Click on finish
Click here , You can see the newly created database
This is the newly created database
Right click the new database , Click on Set as Default Schema Set as the default database for this connection .
Use mysql2 Test database connection
install mysql2
npm i mysql2 sequelize -S
Database configuration file
// src\config\envs\dev.js
module.exports = {
// mysql Configuration of
mysqlConfig: {
host: 'localhost',
user: 'root',
password: 'xiaowei123',
port: '3306',
database: "imooc_logo_course"
}
}
mysql2 Connect the test
// src\db\mysql2.js
const mysql = require('mysql2/promise')
const { mysqlConfig } = require('../config/envs/dev')
// mysql2 Connect the test
async function testMysqlConn() {
const connection = await mysql.createConnection(mysqlConfig)
const [rows] = await connection.execute('select now();')
return rows
}
// It can be executed directly node src/db/mysql2.js To test
; (async () => {
const rows = await testMysqlConn()
console.log(' ~ rows', rows);
})()
module.exports = testMysqlConn
Console execution node src/db/mysql2.js , Print the current time to indicate that the database connection test is successful
Then let's write a route for further testing
// src\routes\index.js
const router = require('koa-router')()
const packageInfo = require('../../package.json')
const testMysqlConn = require('../db/mysql2')
const ENV = require('../utils/env')
// Test database connection
router.get('/api/db-check', async (ctx) => {
// test mysql Database connection
const mysqlRes = await testMysqlConn()
ctx.body = {
errno: 0,
data: {
name: 'biz editor server',
version: packageInfo.version,
ENV,
mysqlConn: mysqlRes.length > 0
}
}
})
module.exports = router
// src\utils\env.js
// environment variable
const ENV = process.env.NODE_ENV || ''
module.exports = {
ENV,
isPrd: ENV === 'production',
isPrdDev: ENV === 'prd_env',
idDev: ENV === 'dev',
isTest: ENV.indexOf('test') === 0,
isTestLocal: ENV === 'test_local',
isTestRemote: ENV === 'test_remote'
}
perform npm run start Turn on the service , And then visit http://localhost:3000/api/db-check, give the result as follows , This indicates that the server connection was successful .
Use Sequelize Test database connection
To configure sequelize , Connect mysql
// src\db\seq\seq.js
const Sequelize = require("sequelize")
const { mysqlConfig } = require('../../config/envs/dev')
const { isPrd, isTest } = require('../../utils/env')
// Connection configuration
const { database, user, password, host, port } = mysqlConfig
const conf = {
host,
port,
dialect: 'mysql'
}
// The test environment does not print logs
if (isTest) {
conf.logging = () => { } // The default is console.log
}
// Online environments use connection pools
if (isPrd) {
conf.pool = {
max: 5, // The maximum number of connections in the connection pool
min: 0, // Minimum number of connections in the connection pool
idle: 1000, // If a thread 10s If not used in , Just release the thread
}
}
// Create connection
const seq = new Sequelize(database, user, password, conf)
module.exports = seq
Database connection test
// src\db\seq\utils\conn-test.js
const seq = require('../seq')
// Test connection , Direct operation node src/db/seq/utils/conn-test.js
seq.authenticate()
.then(() => {
console.log(' ~ ok');
})
.catch(() => {
console.log(' ~ fail',);
})
.finally(() => {
console.log(' ~ finally',);
process.exit()
})
Console execution node src/db/seq/utils/conn-test.js , Print ok This indicates that the database connection test is successful
Synchronization of model and data table
You need to synchronize the database before the service starts , Then start the service
// bin\www
var syncDb = require('../src/db/seq/utils/sync-alter.js')
// Sync first mysql Data sheet
syncDb().then(() => {
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
})
Synchronize the business code of the database , By modifying the data table , The data will not be emptied , To compare safety
// src\db\seq\utils\sync-alter.js
const path = require('path')
const simpleGit = require('simple-git')
const seq = require('../seq')
const { isDev } = require('../../../utils/env')
// Get all seq model
require('require-all')({
dirname: path.resolve('src', 'models'), // src/models There may be mongoose Of model , But it doesn't matter if you get it here
filter: /\.js$/,
excludeDirs: /^\.(git|svn)$/,
recursive: true, // recursive
})
// Synchronization tables
async function syncDb() {
let needToSyncDb = true
// For development environments only !!!
if (isDev) {
// Under development environment , Frequent changes , Synchronize the data table every time you restart , Too much consumption
// therefore , Under development environment , Determine whether to modify src/models The content in ?
// If it is , Then synchronize the data table . otherwise , No need to synchronize data tables .
const git = simpleGit()
// obtain git status Revised documents ,modified The format is as follows [ '.gitignore', 'package.json', 'src/models/README.md' ]
const { modified, not_added: nodeAdded, created, deleted, renamed } = await git.status()
const fileChanged = modified
.concat(nodeAdded)
.concat(created)
.concat(deleted)
.concat(renamed)
if (fileChanged.length) {
// Here we are , explain git status There are changes
// Has it been changed db Related documents
const changedDbFiles = fileChanged.some(f => {
// Changed src/models , Need to synchronize the database
if (f.indexOf('src/models/') === 0) return true
// Changed src/db/seq , Need to synchronize the database
if (f.indexOf('src/db/seq/') === 0) return true
// Other situations , Out of sync
return false
})
// No change db file , No synchronization required
if (!changedDbFiles) needToSyncDb = false
}
// If git status No changes , Synchronize the data table as usual , important !!!
}
if (needToSyncDb) {
await seq.sync({ alter: true })
}
}
module.exports = syncDb
Creating a data model
encapsulation sequelize type
// src\db\seq\types.js
const Sequelize = require('sequelize')
module.exports = {
STRING: Sequelize.STRING, // VARCHAR(255)
TEXT: Sequelize.TEXT, // TEXT
INTEGER: Sequelize.INTEGER,
BOOLEAN: Sequelize.BOOLEAN,
DATE: Sequelize.DATE,
}
Test create a user module
// src\models\UserModel.js
const seq = require('../db/seq/seq')
const { STRING, DATE, BOOLEAN } = require('../db/seq/types')
const User = seq.define('user', {
username: {
type: STRING,
allowNull: false,
unique: 'username', // Do not use unique: true, https://www.chaoswork.cn/1064.html
comment: ' user name , only ',
},
password: {
type: STRING,
allowNull: false,
comment: ' password ',
},
phoneNumber: {
type: STRING,
allowNull: false,
unique: 'username',
comment: ' cell-phone number , only ',
},
nickName: {
type: STRING,
comment: ' nickname ',
},
gender: {
type: STRING,
allowNull: false,
defaultValue: 0,
comment: ' Gender (1 men ,2 women ,0 A secret )',
},
picture: {
type: STRING,
comment: ' Head portrait , Picture address ',
},
city: {
type: STRING,
comment: ' City ',
},
latestLoginAt: {
type: DATE,
defaultValue: null,
comment: ' Last login time ',
},
isFrozen: {
type: BOOLEAN,
defaultValue: false,
comment: ' Whether the user is frozen ',
},
})
module.exports = User
perform npm run dev, Start the service
You can see that the database already has users Watch .
边栏推荐
- Pytorch oserror: DLL load failed: problem solving
- 09 combination mode
- 进程状态汇总
- PHP online common color comparison table
- Xshell远程服务器tensorboard/visdom的本地可视化方法【亲测一步有效】
- 【node】理论+实践让你拿下session、cookie
- Why can MySQL indexes improve query efficiency so much?
- Solidity from introduction to practice (III)
- Didi's two-sided summary
- [detailed explanation] point multiplication and cross multiplication of neural network matrix (pytorch version)
猜你喜欢

Manually mining XSS vulnerabilities

20 status mode

np.arange与np.linspace细微区别(数据溢出问题)

Spark yard memory resource calculation and analysis (Reference) -- optimized configuration of executor cores, nums and memory

Use record of rabbit nest

OpenCV每日函数 直方图相关(3)

【node】快收下爬虫,我们不再为数据发愁

【详解】神经网络矩阵的点乘与叉乘(pytorch版)

16 interpreter mode

MSSQL injection of SQL injection
随机推荐
Matrix decomposition
My first go program
CF1267G Game Relics
np.arange与np.linspace细微区别(数据溢出问题)
Phpexcel reads the contents of the xls/xlsx table and saves it as a CSV file
User insight into the video industry in January 2022: active users began to pick up under the influence of holidays
10 decoration mode
Deeply analyze the usage of final keyword
threejs实现简单全景看房demo
Php+sql get the field name and detailed attributes of MySQL data table
新型冠狀病毒疫情
面试突击59:一个表中可以有多个自增列吗?
traefik ingress实践
yolov5 export Gpu推理模型导出
Thread. Source code analysis of start() method
嵌入式开发专业术语概念汇总
Flask blog practice - display the navigation menu and home page data of the whole site
深入解析final关键字的用法
微表情数据集汇总(全)
面试突击59:一个表中可以有多个自增列吗?