当前位置:网站首页>[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

image.png

Fill in the database name , Other defaults are fine

image.png

Click here to fill in the password

image.png

Fill in the password set during installation , And then click ok

image.png

Click to test the connection

image.png

Show successfully It's a success

image.png

Close the pop-up window , Click on ok

image.png

This is the database we just added , Click to see

image.png

Click this icon to add the database

image.png

Enter the database name , Choose the encoding , Click on apply

image.png

Continue clicking apply

image.png

Click on finish

image.png

Click here , You can see the newly created database

image.png

This is the newly created database

image.png

Right click the new database , Click on Set as Default Schema Set as the default database for this connection .

image.png

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

image.png

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 .

image.png

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

image.png

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

image.png

You can see that the database already has users Watch .

image.png

原网站

版权声明
本文为[A tailed Warbler]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220904370496.html